以下程序應計算用戶輸入整數的次數。例如:用戶輸入42 42 10 10.程序應該輸出:42發生2次,10發生2次。錯誤的輸出。 C++ primer 1.4.4
問題:代碼將不會輸出數字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;
}
按照原樣使用代碼,您需要輸入一個非數字字符串以及這些數字,您將得到計數而不必輸入新的數字。 – splrs
@splrs,我對編程非常陌生。你能提供一個「非數字字符串」的例子嗎?還是糾正輸出問題所需的代碼示例? – Matt
嘗試輸入10 10 42 42 _z_。這將給你正確的計數,並不會開始另一個,即程序將完成。 – splrs