Solutions for entering multiple strings that can contain spaces

The original way of writing:

#include<bits/stdc++.h>
using namespace std;
int main()
{
    int t;
	cin>>t;
	getchar();//吸收回车符
	while(t--)
	{
		string s;
		getline(cin,s);
		cout<<s<<endl;
	}
	return 0;
} 

Later, in order to speed up the input and output efficiency, the output synchronization and unbundling were turned off, but the above writing method failed, so getchar() was replaced with cin.ignore() to solve this problem.

A common function of cin.ignore() is to clear the contents of the input buffer that ends with a carriage return, eliminating the influence of the previous input on the next input. For example, it can be used like this, cin.ignore(1024, '\n'), usually set the first parameter large enough, so that only the second parameter '\n' works, so this sentence is to clear all characters before the carriage return (including the carriage return) from the input buffer stream.

If no parameter is given by default, the default parameter is cin.ignore(1, EOF), that is, clear one character before EOF, and clear one character before encountering EOF and end.
 

Later writing:

#include<bits/stdc++.h>
using namespace std;
int main()
{
	ios::sync_with_stdio(false);
    cin.tie(0),cout.tie(0);
	int t;
	cin>>t;
	cin.ignore();
	while(t--)
	{
		string s;
		getline(cin,s);
		cout<<s<<endl;
	}
	return 0;
} 

Guess you like

Origin blog.csdn.net/weixin_61725823/article/details/125868572