2013-10-13 80 views
0

我想打開一個文件進行閱讀,然後輸出.txt文件中的內容,對我的代碼有什麼建議?閱讀/輸出文件時遇到問題

string process_word(ifstream &word){ 
    string line, empty_str = ""; 
    while (!word.eof()){ 
     getline(word, line); 
     empty_str += line; 
    } 
    return empty_str; 
} 

int main(){ 
    string scrambled_msg = "", input, output, line, word, line1, cnt; 
    cout << "input file: "; 
    cin >> input; 
    ifstream inFile(input); 
    cout << process_word(inFile); 
} 
+0

'empty_str + = line'本質上是不確定的行爲,因爲你不檢查是否你被允許從'line'閱讀。 –

回答

2

相反的:

while (!word.eof()) { 
    getline(word, line); 
    empty_str += line; 
} 

做:

while (std::getline(word, line)) { 
    empty_str += line; 
} 

,這將是很明智的給你的變數更合適的名字。

0

你的功能可以簡化爲:

#include <iterator> 

std::string process_word(std::ifstream& word) 
{ 
    return std::string{std::istream_iterator<char>{word}, 
         std::istream_iterator<char>{}}; 
} 

int main() 
{ 
    string input; 
    std::cin >> input; 

    std::ifstream inFile(input); 
    std::cout << process_word(inFile); 
} 
+0

我認爲你的'process_word'正如它目前的狀態一樣需要C++ 11的支持,對吧? – LihO

+0

這不會編譯,C++ 11或不。 –

+0

@LihO是的。它確實 – 0x499602D2