输出不正确。 C ++引物1.4.4 [英] Incorrect output. C++ primer 1.4.4
问题描述
以下程序应该计算用户输入整数的次数。例如:用户输入42 42 10 10.程序应该输出:42发生2次,10发生2次。
the following program is supposed to count the number of times a user inputs a integer. example: user inputs 42 42 10 10. the program is supposed to out put : 42 occurs 2 times, 10 occurs 2 times.
问题:代码不会输出数字10的最后结果,直到您输入另一个数字。我已经粘贴下面的代码。这段代码来自c ++的引文。 1.4.4
the problem: the code will not output the last result for the number 10 until you input another number. i have pasted the code below. this code comes from c++ primer. 1.4.4
#include <iostream>
int main()
{
// currVal is the number we're counting; we'll read new values into val
int currVal = 0, val = 0;
// read first number and ensure that we have data to process
if (std::cin >> currVal)
{
int cnt = 1; // store the count for the current value we're processing
while (std::cin >> val)
{ // read the remaining numbers
if (val == currVal) // if the values are the same
++cnt; // add 1 to cnt
else
{ // otherwise, print the count for the previous value
std::cout << currVal << " occurs " << cnt << " times" << std::endl;
currVal = val; // remember the new value
cnt = 1; // reset the counter
}
} // while loop ends here
// remember to print the count for the last value in the file
std::cout << currVal << " occurs " << cnt << " times" << std::endl;
} // outermost if statement ends here
return 0;
}
推荐答案
更正由空格分隔的一系列数字输入。
Your program as-written appears correct for a series of numeric inputs separated by whitespace.
您需要向程序提供文件结束指示,以便退出 while
循环并打印最终数据的计数。在Windows中,您可以通过输入[Ctrl] - [Z]作为新行上的第一个字符来实现。在Linux,UNIX和Mac OS X中,[Ctrl] - [D]的作用类似。
You need to give an end-of-file indication to the program so that it will exit the while
loop and print the count for the final data. In Windows, you can do that by entering [Ctrl]-[Z] as the first character on a new line. In Linux, UNIX and Mac OS X, [Ctrl]-[D] serves a similar purpose.
或者,您可以将您的值集放入文本文件,使用重定向来喂养您的程序。例如,假设您将数据放在与可执行文件相同的目录中名为 data.txt
的文件中。在终端窗口中,您可以按如下方式运行程序:
Alternately, you can put your set of values into a text file and use redirection to feed your program. Suppose, for example, you put your data in a file named data.txt
in the same directory as your executable. In a terminal window, you can run your program as follows:
myprogram < data.txt
如其他人所说,非数字输入也可以代替end的文件。例如,您可以输入 42 42 10 10 fred
,它会输出您期望的结果。这似乎不是程序的意图,但。例如,如果您输入 42 42 10 10 fred 37
,程序将停止在 fred
,并且不会看到 37
As some others have noted, a non-numeric input will also work in place of end of file. For example, you could enter 42 42 10 10 fred
, and it'll output what you expect as well. That doesn't appear to be the intent of the program, though. For example, if you input 42 42 10 10 fred 37
, the program stops at fred
and won't see 37
.
这篇关于输出不正确。 C ++引物1.4.4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!