gpt4 book ai didi

c# - C++ 文件输入输出错误?

转载 作者:行者123 更新时间:2023-11-28 08:21:56 25 4
gpt4 key购买 nike

为什么所有内容都被读取为 0?

    int width = 5;
int height = 5;
int someTile = 1;
char buff[128];


ifstream file("test.txt", ios::in|ios::binary);

if(file.is_open())
{
cout << "open";
}

file.read(buff, sizeof(int));
width = atoi(buff);

file.read(buff, sizeof(int));
height = atoi(buff);

for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
file.read(buff, sizeof(int));
someTile = atoi(buff);
cout << someTile;
}
}

我的文件格式代码是用C#写的,是这样写的:

FileStream stream = new FileStream("test.txt", FileMode.Create);
BinaryWriter writer = new BinaryWriter(stream);
// write a line of text to the file

writer.Write(15);
writer.Write(5);

for (int i = 0; i < 15; i++)
{
for (int j = 0; j < 5; j++)
{
writer.Write(1);
}
}

// close the stream
writer.Close();

最佳答案

在不知道 test.txt 内容的情况下,很难准确地说出,但看起来您正在重复读取 4 个字节(在大多数平台上为 int 的大小)到字符缓冲区/字符串中,然后尝试将其转换为成一个数字。除非您的文件完全由四个以 null 结尾的字节 block 构成,否则我不希望它起作用。

更新:好的,看看你的文件格式,你不是在写字符串,而是在写整数。因此,我希望您能够直接读回您的数字,而无需 atoi

例如:

int value;
file.read((char*)&value, sizeof(int));

value 现在应该包含文件中的数字。要转换您的整个示例,您正在寻找这样的东西:

int width = 5;
int height = 5;
int someTile = 1;

ifstream file("test.txt", ios::in|ios::binary);

if(file.is_open())
{
cout << "open";

file.read(reinterpret_cast<char*>(&width), sizeof(int));
file.read(reinterpret_cast<char*>(&height), sizeof(int));

for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
file.read(reinterpret_cast<char*>(&someTime), sizeof(int));
cout << someTile;
}
}
}

关于c# - C++ 文件输入输出错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5496889/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com