如何读取未知数量的输入? [英] How to read unknown number of inputs?

查看:115
本文介绍了如何读取未知数量的输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用C ++ Primer一书学习C ++。



第1.4.3节中,以下示例代码用于读取未知数

  #include< iostream>。 
int main()
{
int sum = 0,值= 0;
//读取到文件结束,计算所有值的运行总和后读取
,而(std :: cin>>值)
sum + = value; //等于sum = sum + value
std :: cout<< 总和为:<<总和<< std :: endl;
返回0;
}

根据这本书,如果我们输入 3 4 5 6 ,输出将为总和为:18



但是当我在计算机上(带有MinGW的Windows 10 )尝试此操作时,代码不会结束。即使我输入换行符,它也会继续要求输入。仅当我输入 f 之类的非整数输入时,它才起作用。






这是预期的吗?如果是,输入换行符后是否有任何停止的代码?



我对c ++还是很陌生,我已经学习过python,所以遇到了麻烦






感谢和问候。

解决方案

您需要使用文件结尾字符(即Windows上的 CTRL-Z CTRL-D (在Mac / Unix上为>),而不仅仅是通过换行符(例如 Enter )。



简单的 Enter 解释为空格,当读入整数数据类型时, operator>> 将被忽略。


$ b相反,$ b

CTRL-Z /文件结束会使任何 operator>> 失败,并显示错误。 / p>

另请参见此SO答案



注意:输入 f 也会终止循环,因为不考虑 f 有效的整数;因此, std :: cin>>值,其中的类型为 int ,输入内容为 f 也将失败。更准确地说: operator>> 实际上返回对输入流的引用,但是如果读取值失败,则 failbit 在流上设置,然后用布尔表达式(隐式调用 basic_istream :: operator bool())解释流对象返回错误;所以也许这本书的作者不想在书的相应部分解释这些细节:-)


I am learning C++ using the book C++ Primer.

In Section 1.4.3, the following example code about reading the unknown number of inputs is given.

#include <iostream>
int main()
{
  int sum = 0, value = 0;
  // read until end-of-file, calculating a running total of all values read
  while (std::cin >> value)
  sum += value; // equivalent to sum = sum + value
  std::cout << "Sum is: " << sum << std::endl;
  return 0;
}

According to the book, if we give an input of 3 4 5 6, the output will be Sum is: 18

But when I try this on my computer(Windows 10 with MinGW), The code does not end. It just keeps on asking for input even if I enter a newline. It works only when I enter a non-int input like f.


Is this expected? If yes, is there any code that stops after inputting a newline?

I am quite new to c++ and I have already learned python, so getting stuck so early on is quite frustrating.


Thanks and regards.

解决方案

You need to terminate your input by an End-Of-File-character (i.e. CTRL-Z on Windows, CTRL-D on Mac/Unix), not just by an End-Of-Line (i.e. Enter).

A simple Enter is interpreted as white space, which will be simply ignored by operator>> when reading into an integral data type.

CTRL-Z / End-Of-File, in contrast, makes any operator>> fail with an error.

See also this SO answer.

Note: Entering f will also terminate your loop, since f is not considered a valid integral number; Hence, std::cin >> value with value being of type int and an input like f will fail as well. To be more accurate: operator>> actually returns a reference to the input stream, but if reading in a value fails, failbit is set on the stream, and then interpreting the stream object in a boolean expression (implicitly calling basic_istream::operator bool()) returns false; So maybe the author of the book did not want to explain these details at the respective section in the book :-)

这篇关于如何读取未知数量的输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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