2010-11-03 45 views
0

我目前有一个小程序,它会将.txt文件的内容重写为字符串。收集.txt文件的内容作为字符串,C++

但是,我想收集文件的所有内容作为一个单一的字符串,我该怎么做呢?

#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; 


    } 


} 
+0

http://stackoverflow.com/questions/2602013/read-whole-ascii-file-into-c-stdstring – 2010-11-03 07:26:02

回答

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 a std::stringstream来实现。或者,你可以将其添加到std::string逐步与std::getline

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

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

您声明字符串和缓冲区,然后读了,而不是EOF循环中的文件,并添加缓冲区字符串。

3
string stringfile, tmp; 

ifstream input("sourcefile.txt"); 

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

如果要逐行执行,只需使用一个字符串向量。

6
#include <sstream> 
#include <string> 

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

尼斯的可能的复制。我喜欢。 – 2011-07-27 09:24:43

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; 
}