【发布时间】:2013-12-16 22:46:52
【问题描述】:
下面的程序应该计算用户输入整数的次数。示例:用户输入 42 42 10 10。程序应该输出:42 出现 2 次,10 出现 2 次。
问题:在您输入另一个数字之前,代码不会输出数字 10 的最后一个结果。我已经粘贴了下面的代码。此代码来自 c++ 入门。 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;
}
【问题讨论】:
-
按原样使用代码,您需要输入非数字字符串以及这些数字,您将获得计数,而无需输入新数字。
-
@splrs,我对编程很陌生。你能提供一个“非数字字符串”的例子吗?或纠正输出问题所需的代码示例?
-
尝试输入 10 10 42 42 z。这将为您提供正确的计数,并且不会启动另一个,即程序将完成。
-
这本书的这一部分让我想知道为什么这本书会受到如此强烈的推荐:它没有得到很好的解释,它的行为与他们描述的不一样,而且是一个无处不在的教学噩梦。 FWIW,我只是将以下内容放在程序的开头:
std::cout << "Enter space-delimited integers and a letter to finish." << std::endl;这基本上是 Joe Z 的建议之一。不知道你为什么不接受他的回答?
标签: c++ visual-c++