多行且每行不确定个数的数据读取 讨厌的换行和getline()

这篇博客探讨了如何使用C++从输入中读取包含多个数字的多行数据。通过示例代码展示了两种不同的方法:一种是利用`cin`和`getline`结合处理换行,另一种是使用`stringstream`来读取和解析字符串流。文章强调了处理换行符和空格的注意事项,并提供了ACwing平台的代码示例。
摘要由CSDN通过智能技术生成

实例

首行是行数,其余行是数目不等的数据
3 
1 2 5 6 8
1 22
58 3 65 14

读到换行符停止

void init() {
	_read(N); getchar();
	int t;
	
	_for(i, 0, N) {
		char ch = ' ';
		while (ch!='\n') {
			cin >> t;
			ch = getchar();
			//ch=cin.get();等价于上一行
			out(t);
		}
	}

}

字符串流

cin是无法读入换行和空格。cin>>n;getline(str);读取首行会发现cin读到换行符停下,把数字存储到n,但后一句只能读到一个换行符之前的内容,即空行。
void init() {
	_read(N); 
	getchar();//必须去掉,否则会读到首行【空行】
	//cin.ignore();等价于上一行
	int t;
	string str;
	stringstream ss;
	_for(i, 0, N) {
		getline(cin, str);
		ss << str;
		while (ss >> t) {
			out(t);
		}
		ss.clear();
	}

}

AC wing题目

AC代码

#include<vector>
#include<cstring>
#include<iostream>
#include<string>
#include<cmath>
#include<sstream>
#include<algorithm>
using namespace std;

#define _for(i,from,to) for(int i=(from);i<(to);++i)//[from,to)
#define _clear(arr,val) fill(arr.begin(), arr.end(), val);
#define _zero(arr) memset(arr,0,sizeof(arr))
#define out(x) cout<<x<<endl
#define _read(x) cin>>x


typedef pair<int, int> PII;
typedef long long ll;
typedef vector<int> Vec;
const int MAXN = 100002;
/*变量*/

int N;
int vis[MAXN];

int start = 100002;
int again;

/*函数*/
void init();


/*正解*/
int main()
{
	init();
	int stop = 0;

	_for(i, start, again) {
		if (vis[i] == 0) {
			stop = i;
			break;
		}
	}
	cout << stop << " " << again << endl;

	system("pause");
	return 0;
}

void init() {
	_read(N); getchar();
	int t;
	stringstream ss;
	_for(i, 0, N) {
		ss.clear();
		string str;
		getline(cin, str);
		ss << str;

		while (ss >> t) {
			start = min(start, t);
			if (vis[t] == 0)
				vis[t] = 1;
			else {
				again = t;
			}
		}
		

	}

}

/*
5
2 1 1 3 4

*/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值