我需要从文件中获取数据然后想要将其保存在字符串中,在将其保存在字符串中之后我想将数据放在同一个文件中我从哪里得到数据.PROBLEM是在获取数据时,它不是检测我的新数据线。让我们看看这个例子。
我有一个文件“check.txt”,其中的数据是这样的:ABC新行DEF新行XYZ新行
现在我想再次在文件中发送相同的数据,但不是发送相同的数据,而是发送它像这样:ABC DEF XYZ。
如何以1号格式添加回来?
这是我试过的代码:
#include<iostream>
#include<fstream>
using namespace std;
void abc()
{
ifstream fin("check.txt");
string line,line1;
while (fin)
{
getline(fin,line);
line1.append(line.begin(),line.end());
}
fin.close();
ofstream fout;
fout.open("check.txt");
while (fout)
{
{
fout<<line1<<endl;
// fout<<"done"<<endl;
cout<<"done"<<endl;
}
break;
}
fout.close();
}
int main()
{
abc();
}
多么可怕。
试试这个:
当你的程序让每一行将它写入stringstream时,使用相同的循环:
void abc()
{
ifstream fin("check.txt");
string line;
stringstream out;
while (fin)
{
getline(fin, line);
out << line << '\n'; //use character '\n' instead of endl, to avoid flushing the stream every loop.
}
fin.close();
ofstream fout;
fout.open("check.txt");
fout << out.str();
fout.close();
}
当getline读取一行时,它会丢弃换行符。将line
附加到line1
时,您需要重新插入换行符。