Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/139.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 读取/输出文件时出现问题_C++_File_Ifstream - Fatal编程技术网

C++ 读取/输出文件时出现问题

C++ 读取/输出文件时出现问题,c++,file,ifstream,C++,File,Ifstream,我想打开一个文件进行阅读,然后输出.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 s

我想打开一个文件进行阅读,然后输出.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);
}
字符串处理\u单词(ifstream&word){
字符串行,空_str=“”;
而(!word.eof()){
getline(字,行);
空_str+=行;
}
返回空的_str;
}
int main(){
字符串加扰_msg=“”,输入,输出,行,字,行1,cnt;
cout>输入;
ifstream-infle(输入);
不能而不是:

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


为变量指定更合适的名称也是明智的。

您的函数可以简化为:

#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);
}
#包括
std::字符串处理\字(std::ifstream&word)
{
返回std::string{std::istream_迭代器{word},
std::istream_迭代器{};
}
int main()
{
字符串输入;
std::cin>>输入;
标准::ifstream infle(输入);

std::cout
empty\u str+=line
本质上是未定义的行为,因为您不检查是否允许从
line
读取。我认为当前的
process\u word
主体需要C++11支持,对吗?这不编译,C++11或不编译。@BenjaminLindley FixedIt现在编译,但它不是eq单价。它跳过所有空格。
#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);
}