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

用write()函数向文本文件写入数据后,打开文件却是乱码!希望各位指点指点!!!

IT男year 发布于 2013-12-26 13:04, 853 次点击
#include<iostream>
#include<fstream>
using namespace std;
class Student//学生类
{
public:
    Student(float x,float y,float z)//构造函数
    {
        this->x=x;
        this->y=y;
        this->z=z;
    }
    ~Student(){}//析构函数
    void sum()//计算总成绩
    {
        cout<<"总成绩:"<<x+y+z;
    }
private:
    float x;
    float y;
    float z;
};
int main()
{
    Student A(89,90,99);
    fstream out("E:\\c++程序数据\\C.txt");
    if(!out)
    {
        cout<<"文件打开失败!";
    }
    out.write((char *)&A,sizeof(Student));
    out.close();
    return 0;
}
7 回复
#2
peach54602013-12-26 14:37
字符编码有问题?
#3
q2152362132013-12-26 17:16
这个写进去打开必须是乱编
#4
embed_xuel2013-12-26 17:21
呵呵,写进去的是数,而不是ascii码,乱码正常
#5
wangdayong992013-12-26 18:16
// 我换了一个写法输出到C.txt文件中的是A,B,C三个字母,以前是float型,转为char型存入文件时就成乱码了
//

#include "stdafx.h"

#include<iostream>
#include<fstream>
using namespace std;

class Student//学生类
{
public:
    Student(int x,int y,int z)//构造函数
    {
        this->x=x;
        this->y=y;
        this->z=z;
    }
    ~Student(){}//析构函数
    void sum()//计算总成绩
    {
        cout<<"总成绩:"<<x+y+z;
    }
private:
    int x;
    int y;
    int z;
};
int main()
{
    //Student A(89,90,99);
    Student A(65,66,67);
    fstream out("D:\\C.txt");
    if(!out)
    {
        cout<<"文件打开失败!";
    }
    out.write((char *)&A,sizeof(Student));
    out.close();
}
#6
IT男year2013-12-26 18:49
回复 3楼 q215236213
那要怎样做才能达到不是乱码呢???
#7
IT男year2013-12-26 18:49
回复 3楼 q215236213
那要怎样做才能达到不是乱码呢???
#8
TonyDeng2013-12-26 19:03
向文件輸出格式化的數據,而不是二進制數據。
1