(sizeof运算符)编写一个程序,使用sizeof运算符来判断计算机系统上各种数据类型的大小,以字节为单位。将结果写入文件datasize.dat中,这样就可以在以后打印结果了。结果应该以两列的格式显示,左边一列为类型名称,右边一列为类型的大小,如下所示: char 1 unsigned char 1 short int 2 unsigned short int 2 Int 4 unsigned int 4 long int 4 unsigned long int 4 float 4 double 8 long double 10 [注意,读者计算机的内置数据类型大小可能与上面所列的不同。] 试写一段C++代码,完成上面的任务。
时间: 2024-03-18 19:42:26 浏览: 23
以下是代码实现:
```c++
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream outfile("datasize.dat"); // 打开文件
if (!outfile) {
cout << "Error: Failed to create file!" << endl;
return -1;
}
outfile << "char\t\t" << sizeof(char) << endl;
outfile << "unsigned char\t" << sizeof(unsigned char) << endl;
outfile << "short int\t" << sizeof(short int) << endl;
outfile << "unsigned short int\t" << sizeof(unsigned short int) << endl;
outfile << "int\t\t" << sizeof(int) << endl;
outfile << "unsigned int\t" << sizeof(unsigned int) << endl;
outfile << "long int\t" << sizeof(long int) << endl;
outfile << "unsigned long int\t" << sizeof(unsigned long int) << endl;
outfile << "float\t\t" << sizeof(float) << endl;
outfile << "double\t\t" << sizeof(double) << endl;
outfile << "long double\t" << sizeof(long double) << endl;
outfile.close(); // 关闭文件
cout << "Data has been written to file datasize.dat successfully!" << endl;
return 0;
}
```
运行程序后,将会在当前目录下生成一个名为datasize.dat的文件,文件内容为各种数据类型在计算机系统上的大小。