注册 登录
编程论坛 C++教室

文件为乱码输出

wx1144542900 发布于 2013-12-21 19:17, 312 次点击
程序代码:
#include <fstream>
#include <iostream>
using namespace std;
struct student
{
    char name[20];
    int num;
    int age;
    char sex;
};

int main()
{
    student stud[3]={"li",1001,18,'f',"fun",1002,19,'m',"wang",1003,17,'f'};
    ofstream outfile("example.txt",ios::binary);
    if(!outfile)
    {
        cout<<"open error!"<<endl;
        return 1;
    }
    for(int i=0;i<3;i++)
        outfile.write((char *)&stud[i],sizeof(stud[i]));
    outfile.close();
    return 0;

}


用的VC,与编译器有没有关系?
1 回复
#2
xufan2013-12-21 20:41
It seems like this:
程序代码:
int main()
{
    student stud[3]={"li",1001,18,'f',"fun",1002,19,'m',"wang",1003,17,'f'};
    ofstream outfile;
    outfile.open("example.txt",ios::trunc);
    if(!outfile)
    {
        cout<<"open error!"<<endl;
        return 1;
    }
    for(int i=0;i<3;i++)
        outfile<<stud[i].name<<" "<<stud[i].num<<" "<<stud[i].age<<" "<<stud[i].sex<<std::endl;
    outfile.close();
    return 0;

}


 
1