从turbo c++中的二进制文件读取后出现意外输出
Unexpected output after reading from a binary file in turbo c++
在读取文件时写入文件后,会得到意外的输出
我写的代码是:
#include<fstream.h>
#include<conio.h>
#include<string.h>
struct test
{
char que[100];
char ans[20];
};
int main()
{
test s, d;
clrscr();
ofstream out("test.dat", ios::binary | ios::app);
ifstream in("test.dat", ios::binary | ios::in);
strcpy(s.que, "2.How many ways the letters of the word abas be arranged to form words with or without meaning");
strcpy(s.ans, "180");
out.write((char*) &s, sizeof(test));
while(!in.eof())
{
in.getline((char*) &d, sizeof(test));
cout << d.que << 'n' << d.ans;
}
getch();
return 0;
}
我得到的输出是:
2.How many ways the letters of the word abas be arranged to form words with or w
ithout meaning
180
180
这是我处理的输出,中间有一些任意字符。
我做错了什么?为什么我存储在s.ans
中的字符串也被写入s.que
?
我通过以下更改实现了这一点:
- 在写入文件后添加
out.close()
以刷新输出缓冲区 - 将
getline
替换为read
,以便在write
写入字节时检索这些字节。CCD_ 7可能在某些条件下给出不同的结果 -
将已读语句移动到
while
条件:while(in.read((char *) &d, sizeof(test)))
由于循环主体中的read语句in.eof()
不会在读取最后一个test
对象后立即返回true,因此循环将最后执行一次。
相关文章:
- 字符串比较中的意外输出
- 来自 decltype 的意外输出类型
- 字符数组到十六进制字符串的转换 - 意外输出
- 使用 boost::regex 从目录中获取带有一些正则表达式的文件名称时出现意外输出
- 使用后序遍历递归的深度优先搜索会产生意外输出
- C++的意外输出
- 贝金纳C++练习解决方案的意外输出
- 无效* 转换获得意外输出
- 以下程序的意外输出
- 意外输出:矢量矢量(功率集)
- 基本 int 数组提供意外输出
- 线程的意外输出
- 减法中的意外输出
- 带有左移操作员C 的意外输出
- C strncpy意外输出
- 意外输出..函数绑定在虚拟表中的发生方式
- 星号的意外输出
- 已编译的 protobuf 文件的意外输出路径
- 打印对象矢量的意外输出
- 递归函数用于计算 n 个数字之和的意外输出