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

2 回答 2

2

代替:

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

做:

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

给变量起更合适的名称也是明智之举。

于 2013-10-13T20:30:12.100 回答
0

Your function can be simplified to:

#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);
}
于 2013-10-13T20:34:31.490 回答