繁体   English   中英

Cin被跳过并且cin.ignore无法正常工作

[英]Cin is being skipped and cin.ignore is not working

需要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:");

...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM