C/C++ 按换行输入,空格分割(输入输出相关,sacnf,sstream)

题目:按行读入int,换行结束,空格分隔

方法一:scanf,其用法推荐链接

//现在默认用scanf_s,比scanf安全

#include
int main() {
	int a,b;
	while (scanf_s("%d%d", &a,&b) != EOF) {
		printf("%d  %d\n",a,b);
	}
}

方法二:stringstream  不错的 链接

#include
#include
#include//stringstream ss(s);
using namespace std;
int main() {
	string s;
	getline(cin, s);
	int a;
	stringstream ss(s);
	while (ss>>a) {
		cout << a << endl;
	}
	system("pause");
}

其中,gelint还可以手动设置其他符号作为换行符用以分割其他,例如这里可以用来分割空格:

#include
#include
#include//stringstream ss(s);
using namespace std;
int main() {
	string s;
	getline(cin, s);
	int a;
	stringstream ss(s);
/*	while (ss>>a) {
		cout << a << endl;
	}*/
	string line;
	while (getline(ss, line, ' '))//按空格分割
	{
		if (!line.empty())
			cout << line << endl;
	}
	system("pause");
}


祝好~

C/C++ 按换行输入,空格分割(输入输出相关,sacnf,sstream)_第1张图片



你可能感兴趣的:(-----语言相关-----)