Using cin.eof()

旧巷老猫 提交于 2019-12-08 06:24:42

问题


I have some code and I wanted to use cin.eof() to stop my program from reading the input. I was thinking of doing:

char array[10]
while(!cin.eof())
{
  for(int i = 0; i < 10; i++)
  {
    cin >> array[i];
  }
}

And the code goes on. However, when I click '\n', my output is outputted. When i click cntrl + d, (on a UNIX terminal) the program performs the output again and then proceeds to end. How do I get it so that my program stops reading at a newline and prints my output when I type cntrl + d only once?

Thanks.


回答1:


First, cin.eof() doesn't do anything useful until input has failed. You never want to use it at the top of a loop.

Secondly, it's not really clear to me what you are trying to do. Something like:

std::string line;
while ( std::getline( std::cin, line ) ) {
    //  ...
}

perhaps? This will read a line of text into the variable line, until end of file; when you encounter an end of file, the input will fail, and you will leave the loop.



来源:https://stackoverflow.com/questions/12891496/using-cin-eof

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!