cin.ignore() 正在产生不需要的行为

cin.ignore() is producing undesired behavior

本文关键字:不需要 ignore cin      更新时间:2023-10-16

对于以下代码:

#include<bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin >> t;
while(t--)
{
string s;
getline(cin,s);
cout << s << "n";
cin.ignore(1000,'n');
}
return 0;
}

示例输入:

阿拉伯数字

名称1

名称2

预期产出:

名称1

名称2

错误输出:

Name2//后跟空行

我不知道为什么会这样。我尝试了堆栈溢出上给出的所有解决方案,但不幸的是没有一个对我有用。提前谢谢。

cin.ignore()

用于在输入整数后忽略新行。 因此,在cin>>t后使用cin.ignore()

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