下面的程序应该计算用户输入整数的次数。示例:用户输入 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;
}
对于由空格分隔的一系列数字输入,您编写的程序看起来是正确的。
您需要给程序一个文件结束指示,以便它退出while
循环并打印最终数据的计数。在 Windows 中,您可以通过输入 [Ctrl]-[Z] 作为新行的第一个字符来完成此操作。在 Linux、UNIX 和 Mac OS X 中,[Ctrl]-[D] 具有类似的用途。
或者,您可以将一组值放入文本文件中,并使用重定向来提供程序。例如,假设您将数据放入名为data.txt
与可执行文件位于同一目录中。在终端窗口中,您可以按如下方式运行程序:
myprogram < data.txt
正如其他一些人所指出的,非数字输入也可以代替文件末尾。例如,您可以输入42 42 10 10 fred
,它也会输出您期望的内容。但这似乎并不是该计划的意图。例如,如果您输入42 42 10 10 fred 37
,程序停止于fred
并且不会看到37
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)