我有这个程序:
using namespace std;
class Motherboards
{
char Board_Manufacturer_Name[50];
char Socket_Type[50];
char Chipset_Type[50];
char Board_Name[50];
char Feature1[500];
char Feature2[500];
char Feature3[500];
float Price;
public:
void getdata();
void displaydata();
};
void Motherboards::getdata()
{
cout << " Enter Manufacturer Name :\n";
cin.getline(Board_Manufacturer_Name, 50);
cout << "\n Enter the Socket type :\n";
cin.getline(Socket_Type, 50);
cout << "\n Enter the Chipset Type :\n";
cin.getline(Chipset_Type, 50);
cout << "\n Enter the Board Name :\n";
cin.getline(Board_Name, 50);
cout << "\n Enter 3 main features for this Board :\n";
cout << "\n1.) ";
cin.getline(Feature1, 500);
cout << "\n2.) ";
cin.getline(Feature2, 500);
cout << "\n3.) ";
cin.getline(Feature3, 500);
cout << "Price :\n";
cin >> Price;
cout << "\n";
}
void Motherboards::displaydata()
{
cout << " Manufacturer : " << Board_Manufacturer_Name << endl;
cout << " Socket : " << Socket_Type << endl;
cout << " Chipset : " << Chipset_Type << endl;
cout << " Board Name : " << Board_Name << endl;
cout << " Features :\n" << "1.) " << Feature1 << endl
<< "2.) " << Feature2 << endl
<< "3.) " << Feature3 << endl;
cout << " Price :\n" << Price;
cout << "\n";
}
int main()
{
int x;
system("cls");
Motherboards M;
fstream Infile;
Infile.open("MotherboardList.dat", ios::in | ios::out | ios::app);
if (!Infile)
{
cerr << "Error :";
}
cout << "Enter the details of the motherboard that you want to add :\n";
M.getdata();
Infile.write((char*)&M, sizeof(M));
cout << "Do you wanna confirm ?";
M.displaydata();
cin >> x;
cout << "Written :\n";
Infile.read((char*)&M, sizeof(M));
M.displaydata();
Infile.close();
return 0;
}
我得到了这个输出:
为什么我的数据是用一些随机语言(也许是中文?)编写的,我需要更改什么来实际正确地写入数据呢?
我希望文本文件是英文的。另外,我输入的每个数据后不应该有换行符吗?
答案 0 :(得分:0)
您创建的文件不是有效的文本文件,而是二进制文件。 您正在以二进制表示形式将c ++结构的内部编写到文件中。
如果您希望文件是人类可读的,请在写入文件之前将结构序列化为字符串,使用JSON或XML。
如果您希望c程序理解它,请在阅读后反序列化。