天天看點

多行且每行不确定個數的資料讀取 讨厭的換行和getline()

執行個體

首行是行數,其餘行是數目不等的資料

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

*/

           

繼續閱讀