C++ 将textfile全部设置为一行,而不返回新行c++;

C++ 将textfile全部设置为一行,而不返回新行c++;,c++,C++,我有以下文本文件(essai.txt): 我的期望输出: i am a second year student my account number is 1039 19 1 2019 我不知道如何阅读新行返回,我尝试了getline,尝试了阅读空白,但显然它不起作用。。 我的代码: char line[50]; ifstream o("essai.txt"); ofstream s("essai.txt"); while (o >> line) { //Here i am

我有以下文本文件(essai.txt):

我的期望输出:

i am a second year student my account number is 1039 19 1 2019
我不知道如何阅读新行返回,我尝试了getline,尝试了阅读空白,但显然它不起作用。。 我的代码:

char line[50];
ifstream o("essai.txt");
ofstream s("essai.txt");

while (o >> line) {
    //Here i am not figuring it out 
}

以下是您可能成功完成的工作:

std::string line;
std::string single_line;
fstream x("essai.txt");
first_iteration = true;
// Read all the data from the file and accumulate the results into a single line
while (std::getline(x,line)) {
    if(first_iteration) { 
       first_iteration = false;
    }
    else {
        single_line += ' ';
    }
    single_line += line;
}
// Position the file write pointer back to the beginning ...
// (that's most probably not needed at all, since the writing position was
// never changed in the previous code)
x.seekp(std::ios_base:beg);
// ... and write out the formerly accumulated input.
x << single_line;
std::字符串行;
std::字符串单线;
fstream x(“essai.txt”);
第一次迭代=真;
//读取文件中的所有数据,并将结果累积到一行中
while(std::getline(x,line)){
if(第一次迭代){
第一次迭代=假;
}
否则{
单线+='';
}
单线+=线;
}
//将文件写入指针放回起始位置。。。
//(这很可能根本不需要,因为写作的位置是
//以前的代码中从未更改)
x、 seekp(标准::ios_base:beg);
// ... 并写出以前累计的输入。

x简单:
while(std::getline(o,line)){s不会
流s(“essai.txt”);
覆盖文本文件?@melpomene很好。你不能在读取文件的同时写入文件(至少不建议这样做)。先读入字符串,然后在完成所有读取后再写入。或者只使用两个不同的文件名。有两个文件可以工作,一个用于读取,另一个用于写入,但我不能在同一个文件上执行吗?可以删除
first_iteration
变量,并将循环简化为:
if(std::getline)(x,单线){while(std::getline(x,line)){single_line+='';single_line+=line;}}
std::string line;
std::string single_line;
fstream x("essai.txt");
first_iteration = true;
// Read all the data from the file and accumulate the results into a single line
while (std::getline(x,line)) {
    if(first_iteration) { 
       first_iteration = false;
    }
    else {
        single_line += ' ';
    }
    single_line += line;
}
// Position the file write pointer back to the beginning ...
// (that's most probably not needed at all, since the writing position was
// never changed in the previous code)
x.seekp(std::ios_base:beg);
// ... and write out the formerly accumulated input.
x << single_line;