.txt文件显示中文符号/ c ++

时间:2015-01-08 19:02:13

标签: c++

所以我用C ++编写这个程序用于学校,一切看起来都没问题,直到我打开.txt文件...所有我能看到的都是中文符号..任何有想法的人?

这是我的代码。不要介意未完成的搜索功能和其他内容。

#include <iostream>
#include <fstream>

using namespace std;

fstream data_file;
struct depositor
{
    char name[20];
    char last_name[30];
    char address[60];
};

void add_depositor(depositor p_Info);
void search_depositor();

void add_depositor(depositor p_Info)
{
    data_file.open("Data.txt", ios::app);
    if (data_file.fail())
    {
        cout << "Error while opening the file!";
        exit(1);
    }
    else
    {
        data_file.write((char*)(&p_Info), sizeof(depositor));
        data_file.close();
    }
}

int menu()
{
    int choice;
    do
    {
        cout << "\n* Menu *";
        cout << "\n* 1. Add depositor! *";
        cout << "\n* 2. Search for depositor! *";
        cout << "\n* 3. Exit program! *";
        cout << "\n* Enter your choice: ";
        cin >> choice;
        cout << "\n* You chose: " << choice;
    } while (choice < 1 || choice > 4);
    return choice;
}
void main()
{
    depositor p; int choice;
    do
    {
        choice = menu();
        switch (choice)
        {
        case 1: cout << "\n Enter first name: ";
            cin >> p.name;
            cout << "\n Enter last name:  ";
            cin >> p.last_name;
            cin.clear();
            cin.ignore(2000, '\n');
            cout << "\n Enter address: ";
            cin.getline(p.address, 60);
            add_depositor(p); break;
        case 2: cout << "";
        default: cout << "\n* End of program! *";
        }
    } while (choice != 4);
}

这就是我在txt文件中得到的结果:

2 个答案:

答案 0 :(得分:1)

将对象数据写入文件的方式:

  data_file.write((char*)(&p_Info), sizeof(depositor));

存储的数据不会被编码以供文本编辑器读取。然而,它可以用于对象序列化以便以后检索。

以文本形式存储数据,可以在记事本中看到:

 data_file << p_Info.name << " "<<p_Info.last_name<<" " << p_Info.address << "\n";

以这种方式,数据以ASCII格式存储。

如果您需要序列化对象,

data_file.open("Data.dat", ios::app | ios::binary); //Its not a text file anymore and has to be opened in binary mode.
if(!data_file){
  cout<<"\nError";
}
else{
  data_file.write((char*)(&p_Info), sizeof(depositor));
}
data_file.close();

答案 1 :(得分:1)

我认为你的问题是你只是将你结构中的任何内容转储到文本文件中(无论是否是好的数据)。您可能希望使用&lt;&lt;空格分隔各个方法和输出。而不是写。

data_file << p_Info.name << ' ' << p_Info.last_name << ' ' << p_Info.address;