You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++程序while循环后代码未执行,如何输入获取完整输出?

解决C++统计重复数字程序无法输出最后一组结果的问题

问题背景

使用《C++ Primer》中的这段统计重复数字次数的代码:

#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;
}

在Mac本地终端或在线编译器运行时,输入1 1 2 2 2 3 3 3 3后,仅输出:

1 occurs 2 times
2 occurs 3 times

无法输出最后一组3 occurs 4 times的结果,尝试按回车和Ctrl+D无效,需解决输入方式问题。

原因分析

程序中的while (std::cin >> val)会持续读取整数输入,直到遇到**输入结束符(EOF)**或输入非整数内容导致读取失败,才会退出循环,进而执行循环外的最后一行输出语句。之前的操作没有正确触发EOF,导致循环未退出,最后一行代码未执行。

解决方法

1. Mac本地终端操作

输入完所有数字后:

  • 先按回车换行,确保光标处于新行开头;
  • 按下Ctrl+D发送EOF信号,此时循环会退出,程序将输出最后一组数字的统计结果。

注:部分终端环境下,可能需要连续按两次Ctrl+D才能触发EOF。

2. 在线编译器操作

不同在线编译器的EOF触发方式不同,常见两种方式:

  • 查找编译器界面的EOF按钮(部分在线编辑器会提供专门的输入结束按钮),点击即可发送EOF;
  • 在输入的最后添加一个非整数内容(比如字母q),此时std::cin >> val读取失败,循环退出,程序会输出最后一组统计结果。

通用替代方案

无论本地还是在线环境,都可以在输入序列的最后添加一个非整数字符(如q、x等),例如输入1 1 2 2 2 3 3 3 3 q,这样cin读取到字母时会失败,循环终止,自动执行最后一行输出代码。

内容的提问来源于stack exchange,提问作者IronManAYaad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 06:03:10