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

C++ tilstart递归函数无法读取文件内容的问题求助

C++递归读取文件问题解决

我帮你瞅了瞅代码,发现几个关键问题导致程序读不到文件内容,咱们一步步来修正:

问题点分析

  • 重复打开文件导致流状态异常:你在main函数里先通过ifstream files("input13.txt");完成了文件流的初始化和打开操作,紧接着又调用files.open("input13.txt");,这会让文件流进入错误状态,后续的file >> start根本读不到任何内容,start一直是空字符串,递归下去必然栈溢出,这也是你不得不注释递归调用的原因。
  • 缺少读取失败的终止逻辑:就算文件正常打开,如果文件里没找到"start"字符串,递归会无限执行直到栈溢出,所以必须添加判断,当读取失败(比如到文件末尾)时直接终止递归。

修正后的代码

#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
using namespace std;

void tilstart(ifstream& file) {
    string start;
    // 先判断文件是否还能正常读取
    if (!(file >> start)) {
        // 读取失败(到末尾或出错),直接返回
        cout << "\n已到文件末尾,未找到\"start\"" << endl;
        return;
    }
    cout << "读到单词:" << start << endl;
    if (start == "start") {
        cout << "找到目标字符串\"start\",终止递归" << endl;
        return;
    }
    // 正常递归调用
    tilstart(file);
}

int main() {
    ifstream files("input13.txt");
    // 只需要初始化时打开一次,不需要再次调用open
    if (files.is_open()) {
        tilstart(files);
    } else {
        cout << "无法打开文件!" << endl;
    }
    return 0;
}

测试效果

当input13.txt内容为going there start h f t时,程序运行后会输出:

读到单词:going
读到单词:there
读到单词:start
找到目标字符串"start",终止递归

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 23:52:37