使用cin.eof() [英] Using cin.eof()

查看:107
本文介绍了使用cin.eof()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些代码,我想使用cin.eof()阻止我的程序读取输入。我正在考虑这样做:

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];
  }
}

然后代码继续进行。但是,当我单击 \n时,将输出我的输出。当我单击cntrl + d时(在UNIX终端上),程序再次执行输出,然后结束。如何获取它,以便我的程序仅在一次键入cntrl + d时停止在换行符处读取并输出我的输出?

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?

谢谢。

推荐答案

首先, cin.eof()在输入失败之前不会做任何有用的事情。
您永远不想在循环的顶部使用它。

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 ) ) {
    //  ...
}

也许吗?这会将一行文本读入变量 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.

这篇关于使用cin.eof()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆