为什么此代码从标准输入中少一个输入?

why this code takes one less input from standard input?

本文关键字:一个 输入 代码 标准输入 为什么      更新时间:2023-10-16

给出输入为:

输入: 3 1 2 3 4 5 6 7 8 9 10 11 12 预期输出: 1 2 3 4 5 6 7 8 9 10 11 12 但它
给出了输出-
1 2 3  4 5 6 7 为什么
不给出最后一行?我的代码中是否有任何错误?
#include <iostream>
#include<stdlib.h>
#include<string.h>
using namespace std;
int main() {
int t;
cin>>t;
while(t--)
{   string str;
getline(cin,str,'n');
cout<<str<<endl;
}
return 0;
}

这是因为cin>>t不读取行尾。第一次调用getline时,您得到一个空字符串。

我可以随手想到几种解决这个问题的方法。首先是跳过第一个数字末尾的空格,因为换行符算作空格。不幸的是,这也将跳过下一行开头的空格。

cin >> t >> std::ws;

另一种方法是使用getline跳过行尾并忽略您返回的字符串。

cin >> t;
getline(cin, str, 'n');