回 帖 发 新 帖 刷新版面

主题:这个程序编译能通过,但是运行后,在D盘建立的TXT文档是空的。没有预期输入的数据

如题,希望大家帮下忙;
#include <iostream>
#include <fstream>
#include <ostream>
using namespace std;
class cstudent
{
    private:
        int num;            //学号
        char name[3];        //姓名
        char sex;            //性别,男为M,女为F
        int age;            //年龄
        int mscore;            //数学成绩
        int cscore;            //计算机成绩
        int escore;            //英语成绩
        float ascore;        //平均成绩
        float all;            //总成绩
    public:
        void get();                        //从文件中读取学生信息
        void send();                    //向文件中输入学生信息
        void output1();                    //输出信息
        void fun();                        //计算平均成绩和总成绩
void input();                    //输入数据
        
};ofstream outfile;
ifstream infile;

void cstudent::fun()
{    
    all=mscore+cscore+escore;cout<<"总成绩:"<<all<<endl;
    ascore=all/3;cout<<"平均成绩:"<<ascore<<endl;
}

void cstudent::send()
{

    outfile<<"学号:";            outfile<<num;        outfile<<endl;
    outfile<<"姓名:";            outfile<<name;        outfile<<endl;
    outfile<<"性别:";            outfile<<sex;        outfile<<endl;
    outfile<<"年龄:";            outfile<<age;        outfile<<endl;
    outfile<<"数学成绩:";        outfile<<mscore;    outfile<<endl;
    outfile<<"计算机成绩:";        outfile<<cscore;    outfile<<endl;
    outfile<<"英语成绩:";        outfile<<escore;    outfile<<endl;
    outfile<<endl;
}

void cstudent::output1()
{
    cout<<"学号:";            cout<<num;        cout<<endl;
    cout<<"姓名:";            cout<<name;    cout<<endl;
    cout<<"性别:";            cout<<sex;        cout<<endl;
    cout<<"年龄:";            cout<<age;        cout<<endl;
    cout<<"数学成绩:";            cout<<mscore;    cout<<endl;
    cout<<"计算机成绩:";            cout<<cscore;    cout<<endl;
    cout<<"英语成绩:";            cout<<escore;    cout<<endl;
}



void cstudent::input()
{
    cout<<"学号:";            cin>>num;        
    cout<<"姓名:";            cin>>name;    
    cout<<"性别:";            cin>>sex;        
    cout<<"年龄:";            cin>>age;        
    cout<<"数学成绩:";            cin>>mscore;    
    cout<<"计算机成绩:";            cin>>cscore;    
    cout<<"英语成绩:";            cin>>escore;    
}




void main()
{    
    cstudent a[2];
    ofstream outfile("D:\\学生信息.txt",ios::out);
        for (int i=0;i<2;i++)
            {
            a[i].input();
            a[i].send();
            cout<<endl;
            }
    outfile.close();
    ifstream infile("D:\\学生信息.txt",ios::in);
        for (i=0;i<2;i++)
        {
            cout<<"No."<<i+1<<endl;
            a[i].output1();
            a[i].fun();
            cout<<endl;
        }

}
    
    
    


    

回复列表 (共2个回复)

沙发

全局的ofstream outfile;被主函数的同名变量覆盖了

板凳


一、用操作符“<<”向文件输出数据,数据项之间要用空格字符串“ ”分开, 如:
outfile << 数据1 << " " << 数据2 << std::endl;
二、在全局作用域定义了流对象, 在主函数中,不能重复定义,只需用open()关联到文件即可,如:outfile.open("学生信息.txt").

我来回复

您尚未登录,请登录后再回复。点此登录或注册