簡體   English   中英

輸出不正確。 C ++ primer 1.4.4

[英]Incorrect output. C++ primer 1.4.4

以下程序應該計算用戶輸入整數的次數。 例如:用戶輸入42 42 10 10.程序應該輸出:42次發生2次,10次發生2次。

問題:在輸入另一個數字之前,代碼不會輸出數字10的最后結果。 我已粘貼下面的代碼。 此代碼來自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;
}

所寫的程序對於由空格分隔的一系列數字輸入顯示正確。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM