使用ofstream以二进制方式写入四个double类型的数,用ifstream逐行读出的时候读出了5个数字
时间: 2024-05-10 17:20:44 浏览: 20
这可能是因为在写入时没有使用二进制模式打开文件。在默认情况下,ofstream使用文本模式打开文件,这会导致在写入double类型的数时发生换行符的转换,从而增加了文件的大小。在读取时,如果使用文本模式打开文件,则会将换行符解释为额外的数字。因此,需要将ofstream和ifstream都以二进制模式打开文件,以确保在读写double类型的数时不会发生任何转换。以下是示例代码:
写入文件:
```
#include <iostream>
#include <fstream>
using namespace std;
int main() {
double a = 1.23, b = 4.56, c = 7.89, d = 0.12;
ofstream file("data.bin", ios::binary);
file.write(reinterpret_cast<char*>(&a), sizeof(double));
file.write(reinterpret_cast<char*>(&b), sizeof(double));
file.write(reinterpret_cast<char*>(&c), sizeof(double));
file.write(reinterpret_cast<char*>(&d), sizeof(double));
file.close();
return 0;
}
```
读取文件:
```
#include <iostream>
#include <fstream>
using namespace std;
int main() {
double a, b, c, d;
ifstream file("data.bin", ios::binary);
file.read(reinterpret_cast<char*>(&a), sizeof(double));
file.read(reinterpret_cast<char*>(&b), sizeof(double));
file.read(reinterpret_cast<char*>(&c), sizeof(double));
file.read(reinterpret_cast<char*>(&d), sizeof(double));
file.close();
cout << a << " " << b << " " << c << " " << d << endl;
return 0;
}
```
在这个例子中,使用reinterpret_cast将double类型的指针转换为char类型的指针,以确保以二进制方式读写数据。