我想知道在用C ++读取或写入文件时如何移动到下一行。我尝试使用seekp从一行移动到另一行,但它只是在同一行中向前移动了一个字符空间。
ofstream writer;
ifstream reader;
int loop;
string test;
writer.open("SU.txt");
cout << "Enter String 1" << endl;
getline(cin, test);
writer.seekp(0);
writer << test;
cout << "Enter String 2" << endl;
getline(cin, test);
writer.seekp(1);
writer << test;
cout << "Enter String 3" << endl;
getline(cin, test);
writer.seekp(2);
writer << test;
cout << "Writer Complete!" << endl;
writer.close();
reader.open("SU.text");
for (loop = 0; loop <= 2; loop++) {
reader >> test;
cout << test << endl;
}
如果我输入以下字符串作为输入,
Hello
Welcome
Goodbye
我将在该文件中获得的输出是,
HWGoodbye
所以我想知道在读取或写入文件时如何从一行移动到另一行。谢谢!
答案 0 :(得分:0)
每次写入后都不需要seek
writer
ofstream
,只需在每次写入结束时添加std::endl
即可,即:
cout << "Enter String 1" << endl;
getline(cin, test);
writer << test << std::endl;