将.txt文件的内容收集为字符串C ++

时间:2010-11-03 06:44:29

标签: c++ string file-io text-files file-read

我目前在这里有一个小程序,它会将.txt文件的内容重写为字符串。

但是我想将文件的所有内容收集为单个字符串,我该如何解决这个问题呢?

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


using namespace std;


int main () {
    string file_name ; 


    while (1 == 1){
        cout << "Input the directory or name of the file you would like to alter:" << endl;
        cin >>  file_name ;


        ofstream myfile ( file_name.c_str() );
        if (myfile.is_open())
        {
        myfile << "123abc";

        myfile.close();
        }
        else cout << "Unable to open file" << endl;


    }


}

5 个答案:

答案 0 :(得分:6)

#include <sstream>
#include <string>

std::string read_whole_damn_thing(std::istream & is)
{
    std::ostringstream oss;
    oss << is.rdbuf();
    return oss.str();
}

答案 1 :(得分:5)

你声明一个字符串和一个缓冲区然后用while而不是EOF循环读取文件并将缓冲区添加到字符串。

答案 2 :(得分:4)

libstdc ++人有一个good discussion of how to do this with rdbuf

重要的部分是:

std::ifstream in("filename.txt");
std::ofstream out("filename2.txt");

out << in.rdbuf();

我知道,你问过将内容放入string。您可以通过out std::stringstream来实现这一目标。或者您可以使用std::getline

逐步将其添加到std::string
std::string outputstring;
std::string buffer;
std::ifstream input("filename.txt");

while (std::getline(input, buffer))
    outputstring += (buffer + '\n');

答案 3 :(得分:3)

string stringfile, tmp;

ifstream input("sourcefile.txt");

while(!input.eof()) {
    getline(input, tmp);
    stringfile += tmp;
    stringfile += "\n";
}

如果你想逐行进行,只需使用字符串向量。

答案 4 :(得分:1)

您还可以在将每个字符分配给字符串时迭代并读取文件,直到达到EOF。

以下是一个示例:

#include "stdafx.h"
#include <iostream>
#include <fstream>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    char xit;
    char *charPtr = new char();
    string out = "";
    ifstream infile("README.txt");

    if (infile.is_open())
    {
        while (!infile.eof())           
        {
            infile.read(charPtr, sizeof(*charPtr));
            out += *charPtr;
        }
        cout << out.c_str() << endl;
        cin >> xit;
    }
    return 0;
}
相关问题