提问人:venkysmarty 提问时间:1/26/2022 最后编辑:user17732522venkysmarty 更新时间:1/27/2022 访问量:109
从文件中读取新行并使用流写入 C++ 中的另一个文件。不读取换行符
reading new line from file and writing to another file in C++ using streams. not reading new line
问:
我正在读取 C++ 中的 IO 流,并有以下代码
int main() {
fstream output_file;
output_file.open("cout.txt", ios::out);
fstream input_file;
input_file.open("cin.txt", ios::in);
// backup existing stream buffers
streambuf* cin_old_streambuf = cin.rdbuf();
streambuf* cout_old_streambuf = cout.rdbuf();
// Get output stream buffer of file and redirect to cout
streambuf* output_file_streambuf = output_file.rdbuf();
cout.rdbuf(output_file_streambuf);
// Get input stream buffer of file and redirect to cin
streambuf* input_file_streambuf = input_file.rdbuf();
cin.rdbuf(input_file_streambuf);
/* What ever you do with cout will write to file. */
string line;
getline(cin, line);
cout << line;
getline(cin, line);
cout << line;
getline(cin, line);
cout << line;
getline(cin, line);
cout << line;
}
我的输入文件cin.txt
My name is
ravi
My age is
45
输出文件是cout.txt
My name israviMy age is 45
我的问题是为什么程序没有在输入中读取\n。我的理解是读换行符。我希望输出文件类似于输入文件。请帮助我有什么变化getline
答:
1赞
Winston Hsiao
1/27/2022
#1
虽然确实逐行检索其他文件中的输入,但如果在打印时想要新行,您仍应遵循在行末添加或添加任何一行的标准。getline(cin, line);
cout << line;
"\n"
endl;
cout
代码的最后一部分应如下所示。
getline(cin, line);
cout << line << endl;
getline(cin, line);
cout << line << endl;
getline(cin, line);
cout << line << endl;
getline(cin, line);
cout << line << endl;
评论
My understanding is that getline reads newline.
:它确实从流中提取它,但不会将其附加到字符串中。cout << line << '\n';