为什么这段代码从标准输入中少了一个输入?

why this code takes one less input from standard input?

输入如下:

Input:
    3
    1 2 3 
    4 5 6 7
    8 9 10 11 12
Expected Output:
    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');