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

C++如何逐行读取整个文件内容并赋值给string变量

修改方案

要实现把全量文件内容存入string str后一次性输出,按以下改动即可:

  • 引入<string>头文件,string类型的相关操作依赖这个头文件
  • 定义string类型的str变量,用来存储整个文件的内容
  • 把原有逐字符直接打印到控制台的逻辑,改为把读取到的字符追加到str中;如果追求更简洁高效的实现,也可以直接通过文件流缓冲区一次性读取全部内容,省去逐字符循环的开销
  • 补充说明:原代码里的gets()函数是已经被废弃的不安全函数,容易触发缓冲区溢出,建议替换为cin.getline()读取文件名,功能完全一致、安全性更高

逐字符读取版本(和原有代码逻辑兼容性最高)

#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
    char fileName[30], ch;
    fstream fp;
    string str;
    cout<<"Enter the Name of File: ";
    cin.getline(fileName, 30);
    fp.open(fileName, fstream::in);
    if(!fp)
    {
        cout<<"\nError Occurred!";
        return 0;
    }
    cout<<"\nContent of "<<fileName<<":-\n";
    while(fp>>noskipws>>ch) {
        str += ch;
    }
    fp.close();
    cout << str;
    cout<<endl;
    return 0;
}

高效一次性读取版本(代码更简洁,性能更好)

#include<iostream>
#include<fstream>
#include<string>
#include<sstream>
using namespace std;
int main()
{
    char fileName[30];
    fstream fp;
    cout<<"Enter the Name of File: ";
    cin.getline(fileName, 30);
    fp.open(fileName, fstream::in);
    if(!fp)
    {
        cout<<"\nError Occurred!";
        return 0;
    }
    stringstream sstr;
    sstr << fp.rdbuf();
    string str = sstr.str();
    fp.close();
    cout<<"\nContent of "<<fileName<<":-\n";
    cout << str;
    cout<<endl;
    return 0;
}

两个版本编译运行后效果和原有输出完全一致,所有文件内容都存在str变量里,直接执行cout<<str就能完整打印全部内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 11:51:24