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

C++使用getline读取txt文件内容存入字符串数组问题求助

C++逐行读文件存入数组问题排查与解决方案

问题原因

  • 核心逻辑错误为循环嵌套不当:你将控制下标的for循环套在了while(getline)外层。while(getline(myFile, line))执行时会一次性读完文件所有内容,第一次进入for循环(i=0)时,所有读取到的行都会被反复赋值给str[0],文件读完后getline返回false,后续i=1到i=4的循环中没有内容可读取,因此i不会增加到4。
  • 附加问题:getchar()的注释描述错误,它的作用是清除cin >> filename后输入缓冲区残留的换行符,避免后续读行操作读到空行,不是读取文件名前清空缓冲区。
  • 非必要全局变量使用可能带来额外的变量污染风险。

修复方案

以下为适配你需求的可运行代码,实现读取文件最多5行存入字符串数组,后续遍历所有存入的元素:

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

int main() {
    fstream myFile;
    string filename, line, str[256];
    // 下标变量局部定义更安全
    int i = 0;

    // 1. 提示用户输入文件完整名称
    cout << "Enter the file name to open: ";
    cin >> filename;
    // 用cin.ignore更规范地清除缓冲区残留换行
    cin.ignore();

    // 2. 打开文件用于读取
    myFile.open(filename.c_str(), fstream::in);

    if (!myFile.is_open()) {
        cout << "ERROR: not able to open " << filename << endl;
        return 1;
    }

    // 3. 逐行读取最多5行存入数组,合并循环逻辑
    while (i < 5 && getline(myFile, line)) {
        str[i] = line;
        cout << "String [" << i << "] = " << str[i] << endl;
        i++;
    }
    myFile.close();

    // 4. 遍历数组所有已存入元素的示例
    cout << "\n遍历数组结果:" << endl;
    for (int j = 0; j < i; j++) {
        cout << "str[" << j << "]:" << str[j] << endl;
    }

    return 0;
}

如果你需要读取文件所有行(不限制为5行),只要把循环条件修改为i < 256 && getline(myFile, line)即可,和你定义的str数组最大容量匹配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 05:06:04