codewars 一道题 Highest and Lowest

Problem

In this little assignment you are given a string of space separated numbers, and have to return the highest and lowest number.
输入是一个字符串,输出最大数和最小数。

Note

All numbers are valid Int32, no need to validate them.
There will always be at least one number in the input string.
Output string must be two numbers separated by a single space, and highest number is first.

Solution

#include <string>
#include <sstream>  //这是C++引入的,可以对串流做输入输出处理。
#include <limits>   //这个头文件对应下面的最大值和最小值
using namespace std;
string highAndLow(const string& numbers){
  string number=numbers;
  int max=numeric_limits<int>::min();  //返回编译器允许的最小值
  int min=numeric_limits<int>::max();  //返回编译器允许的最大值
  int temp;
  stringstream ss(numbers);  //ss的值现在是number的值
  while(ss>>temp)
  {
  if(temp<min){min=temp;}
  if(temp>max){max=temp;}
  }
  return to_string(max)+" "+to_string(min);
}

这代码真简洁,每次看到大佬的代码都佩服的不行。
关于stringstream的用法,转载以为大佬的一下代码:
(转载自https://blog.csdn.net/Sophia1224/article/details/53054698)

#include <sstream>
#include <iostream>
using namespace std;
int main() {
	ostringstream out;
	out.put('t');//插入字符
	out.put('e');
	out << "st";   //这里是输入的意思。
	string res = out.str();//提取字符串;
	cout << res << endl;
	return 0;
}
//输出是 test 字符串。

#include<iostream>
#include <sstream> 
using namespace std; 
int main() {
	string test = "-123 9.87 welcome to, 989, test!";
	istringstream iss;//istringstream提供读 string 的功能
	iss.str(test);//将 string 类型的 test 复制给 iss,返回 void 
	string s;
	cout << "按照空格读取字符串:" << endl;
	while (iss >> s) {
		cout << s << endl;//按空格读取string
	}
	cout << "*********************" << endl;

	istringstream strm(test);
	//创建存储 test 的副本的 stringstream 对象
	int i;
	float f;
	char c;
	char buff[1024];

	strm >> i;
	cout << "读取int类型:" << i << endl;
	strm >> f;
	cout << "读取float类型:" << f << endl;
	strm >> c;
	cout << "读取char类型:" << c << endl;
	strm >> buff;
	cout << "读取buffer类型:" << buff << endl;
	strm.ignore(100, ',');
	int j;
	strm >> j;
	cout << "忽略‘,’读取int类型:" << j << endl;
	return 0;
}

在这里插入图片描述
这个里面代码讲解的很细致。大佬。
结束!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

指针的值是地址

觉得还不错,我会继续努力的。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值