【问题标题】:Incorrect output. C++ primer 1.4.4输出不正确。 C++ 入门 1.4.4
【发布时间】: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 &lt;&lt; "Enter space-delimited integers and a letter to finish." &lt;&lt; std::endl; 这基本上是 Joe Z 的建议之一。不知道你为什么不接受他的回答?

标签: c++ visual-c++


【解决方案1】:

对于一系列由空格分隔的数字输入,您编写的程序看起来是正确的。

您需要向程序提供文件结束指示,以便程序退出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

【讨论】:

  • 这是一个很好的答案,应该被接受。坦率地说,这本书的这一部分有点糟糕。
猜你喜欢
  • 1970-01-01
  • 2018-09-13
  • 1970-01-01
  • 2022-11-03
  • 2021-09-01
  • 1970-01-01
  • 2015-04-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多