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

C++文件单词统计程序while循环无法正常终止,需CTRL+C强制停止

问题原因与修复方案

核心错误

你的代码陷入无限等待的原因是:内层循环里用了std::cin.get(ch)读取终端输入,而非你打开的文件流in_stream。程序执行到这里时,会一直等待你在终端输入字符,而非自动读取文件内容,所以必须手动按CTRL+C才能中断。


修复方案一:简化版(利用流的单词读取特性)

std::ifstream的>>运算符本身会自动跳过空白字符(空格、换行、制表符),每次读取一个完整单词。直接用这个特性统计单词数即可,不需要嵌套循环:

#include <fstream>
#include <iostream>
#include <cstdlib>
#include <string>

int main()
{
    char file_name[16];
    std::ifstream in_stream;
    int count = 0;
    std::string next;

    std::cout << "What is the name of the file? ";
    std::cin >> file_name;
    in_stream.open(file_name);

    if (!in_stream.is_open()) {
        std::cout << "Something went wrong when opening your file.";
        exit(1);
    }

    // 每次读取一个单词,读取失败(到文件末尾)时循环自动结束
    while (in_stream >> next) {
        ++count;
    }
    
    in_stream.close();

    std::cout << "The file " << file_name << " contains " << count << " words." << std::endl;

    return 0;
}

修复方案二:逐字符处理(符合你最初的思路)

如果你想保留逐字符判断的逻辑,需要把读取对象换成文件流in_stream,并通过空白字符的切换来统计单词:

#include <fstream>
#include <iostream>
#include <cstdlib>
#include <string>

int main()
{
    char file_name[16];
    std::ifstream in_stream;
    int count = 0;
    char ch;
    bool lastWasWhite = true;

    std::cout << "What is the name of the file? ";
    std::cin >> file_name;
    in_stream.open(file_name);

    if (!in_stream.is_open()) {
        std::cout << "Something went wrong when opening your file.";
        exit(1);
    }

    // 逐字符读取文件内容
    while (in_stream.get(ch)) {
        bool currentIsWhite = (ch == ' ' || ch == '\n' || ch == '\t');
        // 从空白切换到非空白时,判定为新单词的开始
        if (lastWasWhite && !currentIsWhite) {
            ++count;
        }
        lastWasWhite = currentIsWhite;
    }
    
    in_stream.close();

    std::cout << "The file " << file_name << " contains " << count << " words." << std::endl;

    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 10:40:28