C CIN输入要文件
C++ cin input to file
im从C背景学习C 。
我想做的是将控制台输入复制到文件。对于这个proupouse,我这样做:
#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;
}
问题是正确的执行,最后一行不在输出文件中。即:如果我输入
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++文本文件输入
- C++ 中文件输入输出中的长长 v/s int
- 如何修复函数中的 fstream 文件输入以将正确的信息存储在结构数组中?
- 用空格填充 2D 数组(从文件输入)
- 流对象来表示文件输入,然后是标准输入?
- 用精神解析文件输入
- 从文件输入和输出
- 来自文本文件输入 c++ 的向量
- 如何通过键盘或分数文件输入分数
- 了解文件输入和输出,我可以写入文件,但无法从文件打印
- 词频程序 - 文件输入太大?
- 尝试从 csv 文件输入大量数据时出错
- 如何将文件从文件输入到C 中的矩阵中
- 如何从Windows CMD运行可执行文件并将其传递给文件输入的参数参数和重定向
- 如何解析文本文件并使用构造函数中的文件输入来创建对象的容器
- 这是读取文件输入的正确方法吗?
- 如何在 c++ 中使用二进制文件输入/输出读取/写入结构的字符串类型成员
- 如何创建一个具有空值、递减编号系统和.txt文件输入值的二维阵列网格
- C 文件输入流循环问题
- 使用对输入整数的文件输入