3.if条件句--算数字出现次数

 1 #include <iostream>
 2 
 3 int main()
 4 {
 5     // currVal is the number we're counting; we'll read new values into val
 6     int currVal = 0, val = 0;
 7 
 8     // read first number and ensure that we have data to process
 9     if (std::cin >> currVal) {
10         int cnt = 1;  // store the count for the current value we're processing
11         while (std::cin >> val) { // read the remaining numbers 
12             if (val == currVal)   // if the values are the same
13                 ++cnt;            // add 1 to cnt 
14             else { // otherwise, print the count for the previous value
15                 std::cout << currVal << " occurs "
16                     << cnt << " times" << std::endl;
17                 currVal = val;    // remember the new value
18                 cnt = 1;          // reset the counter
19             }
20         }  // while loop ends here
21         // remember to print the count for the last value in the file
22         std::cout << currVal << " occurs "
23             << cnt << " times" << std::endl;
24     } // outermost if statement ends here
25     system("pause");
26     return 0;
27 }

输入:111 111 111 111 22 22 22 22 34 444 444 777 777 (回车)

得到:

还在等着键盘的输入。

原因:cin没有遇到end-of-file

输入:111 111 111 111 22 22 22 22 34 444 444 777 777 (ctrl + Z)(回车)
得到:

结果正常

猜你喜欢

转载自www.cnblogs.com/foremember/p/10470331.html
今日推荐