繁体   English   中英

C ++ cin输入到文件

[英]C++ cin input to file

我从C背景学习C ++。

我想要做的是将控制台输入复制到文件中。 为此,我这样做:

 #include "stdafx.h"
 #include <fstream>
 #include <iostream>
 using namespace std;
 int main()
 {
     ofstream file_out;
     file_out.open("test.txt");
     char char_input;
     while (!cin.eof())
     {
         cin.get(char_input);
         file_out << char_input;
     } 
     file_out.close();
     return 0;
}

事实是正确的执行是最后一行不在输出文件中。 IE:如果我输入

Hello
My Name Is
Lucas
Goodbye!

“再见”不仅出现在文件中

Hello
My Name Is
Lucas

事先感谢。

这通常是反模式(即使在C语言中也是如此):

while (!cin.eof())

这有两个问题。 如果有错误,您将陷入无限循环(尽管我们可以打折阅读字符)。

但是主要的问题是只有在以下事实之后才能检测到EOF:

cin.get(char_input);
// What happens if the EOF just happend.
file_out << char_input;
// You just wrote a random character to the output file.

您需要在读取操作之后而不是之前进行检查。 在将读取写入输出之前,请始终测试读取是否有效。

// Test the read worked as part of the loop.
// Note: The return type of get() is the stream.
//       When used in a boolean context the stream is converted
//       to bool by using good() which will be true as long as
//       the last read worked.
while (cin.get(char_input)) {
    file_out << char_input;
}

我会注意到这可能不是读取输入或写入输出的最有效方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM