【问题标题】:Cin is being skipped and cin.ignore is not working正在跳过 cin 并且 cin.ignore 不起作用
【发布时间】:2019-11-16 23:37:27
【问题描述】:

需要 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

【问题讨论】:

  • 你能给我们举个输入的例子吗?
  • 所以你读取了cin的所有可用输入直到文件末尾,然后你希望能够继续读取它?
  • @SidS 不不,我知道我正在阅读直到文件结束。我想再次使用 cin,但这次是用于用户输入。你懂我的意思吗?对不起,如果这听起来令人困惑
  • 所以你必须想办法取消重定向。
  • @SidS 嗯,我看看能找到什么

标签: c++ stream cin


【解决方案1】:

我相信以下方法会起作用(未经测试):

string line;
while(cin>>line)
{
    cout<<line<<endl;
}

cin.close ();
cin.open ("/dev/tty");  // (or, on Windows, cin.open ("CON:");

...

【讨论】:

    猜你喜欢
    • 2014-06-30
    • 1970-01-01
    • 2014-11-28
    • 1970-01-01
    • 2014-04-01
    • 2017-05-03
    • 2018-04-24
    • 2011-02-04
    • 2013-11-24
    相关资源
    最近更新 更多