2011-05-10 162 views
0

我有一個包含文本的文件。我逐行閱讀整個文件並追加到一個字符串對象。但是當我得到最終的字符串打印出來,我沒有得到整個文件的內容。我相信這是由於特殊字符,如「\ n」,「\ r」,「\ t」等存在讀取文件內容的問題

這裏是我的示例代碼:

// Read lines until end of file (null) is reached 
do 
{ 
    line = ""; 
    inputStream->read_line(line); 

    cout<<"\n "<<line;//here i get the content of each line 
    fileContent.append(line);// here i am appending 
}while(line.compare("") != 0); 
+0

顯示更多的代碼,等,其中聲明'inputStream'和'fileContent'。 – ildjarn 2011-05-10 11:55:21

回答

1

這是用C++將文件讀入內存的方法:

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

int main() { 
    vector <string> lines; 
    ifstream ifs("myfile.txt"); 
    string line; 
    while(getline(ifs, line)) { 
     lines.push_back(line); 
    } 
    // do something with lines 
} 
+0

發生編譯錯誤... – boom 2011-05-10 12:09:16

+0

@iSight不與我的編譯器不同。你遇到了什麼錯誤? – 2011-05-10 12:13:04

+0

對不起,我需要在ifs構造函數中傳遞const char *。 – boom 2011-05-10 12:21:57

1

您必須展示更多代碼才能知道您的問題是什麼。

如果您正在閱讀的整個文件到一個單一的字符串,這是我通常使用的方法:

#include <string> 
#include <fstream> 
#include <iterator> 

std::string read_file(const char *file_name) 
{ 
    std::filebuf fb; 

    if(!fb.open(file_name, std::ios_base::in)) 
    { 
     // error. 
    } 

    return std::string(
     std::istreambuf_iterator<char>(&fb), 
     std::istreambuf_iterator<char>()); 
}