0

私は現在、.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;


    }


}
4

5 に答える 5

6
#include <sstream>
#include <string>

std::string read_whole_damn_thing(std::istream & is)
{
    std::ostringstream oss;
    oss << is.rdbuf();
    return oss.str();
}
于 2010-11-03T06:59:23.387 に答える
5

文字列とバッファを宣言してから、while not EOF ループでファイルを読み取り、文字列にバッファを追加します。

于 2010-11-03T06:57:31.083 に答える
4

libstdc++ の連中は、でこれを行う方法についてよく議論していrdbufます。

重要な部分は次のとおりです。

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

out << in.rdbuf();

内容をstring. outを作成することでそれを行うことができますstd::stringstreamstd::stringまたは、次のように段階的に追加することもできstd::getlineます。

std::string outputstring;
std::string buffer;
std::ifstream input("filename.txt");

while (std::getline(input, buffer))
    outputstring += (buffer + '\n');
于 2010-11-03T06:56:05.987 に答える
3
string stringfile, tmp;

ifstream input("sourcefile.txt");

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

行ごとに実行したい場合は、文字列のベクトルを使用してください。

于 2010-11-03T06:58:56.320 に答える
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;
}
于 2010-11-03T07:37:27.643 に答える