2014-02-13 106 views
1

我想讀一個input.txt文件的內容,並把它放在output.txt文件中,我試圖在下面的代碼中做到這一點,但是我沒有成功,我是新來的C++文件操作,你能告訴我這個怎麼做 ?在C++中,如何讀取文本文件的內容,並將其放入另一個文本文件中?

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

    int main() { 
    string line; 
    std::vector<std::string> inputLines; 
     ifstream myfile ("input.txt"); 
    if (myfile.is_open()) 
    { 
     while (getline (myfile,line)) 
    { 
     cout << line << '\n'; 
     inputLines.push_back(line); 
    } 
    myfile.close(); 
    } 

    else cout << "Unable to open file"; 

    ofstream myfile2 ("output.txt"); 
    if (myfile2.is_open()) 
    { 
    for(unsigned int i = 0;i< inputLines.size();i++) 

    myfile2 << inputLines[i]; 

     myfile2.close(); 
    } 

    return 0; 
    } 

回答

3

在您的代碼中,您不存儲輸入行。首先,通過

std::vector<std::string> inputLines; 

定義字符串的載體,每個輸入行存入您的清單,

inputLines.push_back(line) 

,然後通過遍歷向量的項目進行

寫你的輸入線,輸出
for(unsigned int i = 0;i < inputLines.size();i++) 
myfile2 << inputLines[i] 

PS:你可能需要

#include <vector> 
+0

謝謝你,在上面的程序中,我一行一行地閱讀內容,你能告訴我如何按字符讀取字符,然後打印出來嗎?如果我使用'char'而不是'string'來讀取內容,那麼我還可以使用'vector'還是有其他關鍵字? – user2917559

+0

請看看這也是,http://stackoverflow.com/questions/21767700/c-pointer-to-integer-comparison-error – user2917559

2

必須調用myfile2 << line;while循環中。

相關問題