CIN被跳过,Cin.ignore不起作用

Cin is being skipped and cin.ignore is not working

本文关键字:Cin ignore 不起作用 CIN      更新时间:2023-10-16

i/o重定向,我不能使用fstream。我通过使用"< input.txt"运行可执行文件来使用I/O重定向。在我的程序中,我使用while(cin>>line)通过I/O重定向读取文件。然后我需要cin>>x ,,但是这次是在运行时输入的用户输入。

我已经尝试了cin.ignore, cin.clear().

如果cin用于I/O重定向,是否可以将cin用于同一程序中的用户输入?

/* Not sure if this is necessary but example of input file:
x y z
a b c
j k l
*/
string line;
while(cin>>line)
{
    cout<<line<<endl;
}
//I've tried these 2 lines but cin>>x is still being skipped
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
cout<<"Enter number: ";
int x;
cin>>x;// this is being skipped

我相信以下内容会起作用(未经测试(:

string line;
while(cin>>line)
{
    cout<<line<<endl;
}
cin.close ();
cin.open ("/dev/tty");  // (or, on Windows, cin.open ("CON:");
...