C++ cin 输入到文件

标签 c++

我是从 C 语言背景开始学习 C++。

我想做的是将控制台输入复制到一个文件中。对于这个proupuse我这样做:

 #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;
}

事情是正确的,除了最后一行不在输出文件中。 I.E:如果我输入

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;
}

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

关于C++ cin 输入到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47823964/

相关文章:

c++ - 来自 C 数组的 STL 数组,无需复制

c++ - 冲突的枚举

c++ - Vivado SDK 无法识别#include "math.h"中的函数

c++ - 从规则间隔的数据生成等高线

c++ - C/C++ 中的函数式编程?

c++ - setRawHeader 不遵循 WebView 中的元素

C++ - 非指针类成员何时被销毁?

c++ - 定义私有(private)静态类成员

c++ - 全局 vector 在调用之间清空自身?

c++ - 绘制 8bpp 灰度位图(非托管 C++)