流的奇怪问题.不能存储具有特定值的成员变量的对象
Weird problem with fstream. Cannot store objects with member variables having a certain value
当我尝试存储具有任何值为 13 或 26 或 7 的元素的对象,然后尝试读取此文件时,它只是给出垃圾值。其他值(如 1、64、78(随机值((不会发生这种情况。
我分别使用了ofstream
和ifstream
来保持代码简单。我正在使用旧的编译器(Borland C++(,但我的朋友没有遇到此错误。
#include <iostream.h>
#include <conio.h>
#include <fstream.h>
class xyz
{
public:
int x;
};
void main()
{
xyz a;
a.x = 45; // replace by 45 or 78 it works. Replace by 13, 26 it shows garbage values.
ofstream of;
of.open("file.dat", ios::out||ios::binary);
of.write((char*)&a, sizeof(a));
of.close();
xyz b;
ifstream sf;
sf.open("file.dat", ios::in||ios::binary);
sf.read((char*)&b, sizeof(b));
sf.close();
cout<<b.x;
getch();
}
目前输出将为 45,但如果将其替换为 13 或 26,它将打印垃圾值。
sf.open("file.dat", ios::in||ios::binary);
||
不会做你认为它做的事情。在这里,您需要使用按位或运算符,|
,而不是逻辑运算符||
。
因此,由于此错误,您的文件实际上以文本模式打开,而不是以预期的二进制模式打开。
代码将二进制八位字节 13 和 26 写入文件并将其读回。八进制 13 和 26 由于其历史遗产,在 Microsoft Windows 上的文本文件中具有特殊含义。代码也无法检查read()
的返回值和/或输入流的状态,这本来可以检测到此错误。
这是因为您的代码包含问题,最值得注意的是,您尝试使用||
(逻辑/布尔OR(而不是|
(按位OR(执行按位OR,后者用于像您一样将标志添加在一起。
其他需要注意的事情(尽管我不确定它们是问题的直接来源(: - 调用标准元素时忘记使用std::
- 主要总是需要返回int
键入下次,启用更多编译器标志以帮助查找代码中的问题。 我不知道 turbo-c++,但在 g++ 中,您可以添加-Wall -Wextra
以获取更多警告。 还有更多功能可供启用!
这是您的代码,其中包含我提到的一些更改
#include <fstream>
#include <iostream>
class xyz
{
public:
int x;
};
int
main()
{
xyz a;
a.x = 45;
std::ofstream of;
of.open("file.dat", std::ios::out | std::ios::binary);
of.write((char*)&a, sizeof(a));
of.close();
xyz b;
std::ifstream sf;
sf.open("file.dat", std::ios::in | std::ios::binary);
sf.read((char*)&b, sizeof(b));
sf.close();
std::cout << b.x;
}
请注意,如果您无法访问"最新"编译器(我假设您停留在一个版本上(,则有几个在线编译器允许您编译代码: - https://wandbox.org - https://gcc.godbolt.org/ -等
你的编码实际上不是正确的,这是基于你的代码的解释:
#include<iostream>
#include<fstream>
#include<ios>
using namespace std;
struct xyz{
int x;
};
int main(){
xyz a, b;
a.x=134;
fstream of;
of.open("file.dat"s, ios::out|ios::binary); // bitwise or
of.write((const char*)&a, sizeof(a));
of.close();
ifstream sf;
sf.open("file.dat"s, ios::in|ios::binary);
sf.read((char*)&b, sizeof(b));
sf.close();
cout<<b.x<<endl;
return 0;
};
- 你能重载对象变量名本身返回的内容吗
- 将包含C样式数组的对象初始化为成员变量(C++)
- 将地址分配给本地指针后,公共对象的变量将消失
- 为什么我们再次从结构对象创建结构变量?
- 如何在初始化列表中的构造函数之后初始化变量/对象?
- 从变量对象指向基对象
- C++ - 我可以创建编译时变量对象吗?
- 动态数组添加元素而不创建结构变量/对象
- Visual Studio C++ 编译器在局部变量对象上的奇怪行为
- 其中定义函数的静态局部变量对象
- QT良好的全局变量/对象处理
- r 值的匿名变量对象与真实对象
- QT 测试 - 变量/对象失去价值
- 访问私有变量对象
- C++访问具有相同名称的变量/对象的命名空间中的全局变量/对象
- C++-访问全局变量对象
- 表达式必须具有类类型:c++,将实例变量对象作为指针传递(点表示法参数)
- C++变量/对象和堆内存管理
- 如何在每次迭代中创建一个新变量/对象的循环
- 初始化现有变量/对象的新构造函数