GubE
2019-12-17 23:51
采纳率: 91.7%
浏览 85

关于io输入输出流,为什么输入到文件出错

class student
{

public:

string name;

int age;

public:

void grade() {

    int i = 0;

    string name;

    cout << "name:";

    cin >> name;

    cout << "age:";

    cin >> age;

    cout << "name:" << name << '/t' << "age:" << age << endl;

}

};

int main() {

student a[3];

int i = 0;

ofstream fout("e:\\text.txt");

for (i; i < 3; i++) {

    a[i].grade();

fout << "name:" << a[i].name << "age:" << a[i].age << endl;

};

fout.close();

}

图片说明

//为什么name没有被记录下来?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • blownewbee 2019-12-18 09:50
    已采纳

    因为你又定义了一个叫做name的局部变量,所以没有存入成员变量name里面。

    // Q1030229.cpp : Defines the entry point for the console application.
    //
    
    #include "stdafx.h"
    
    #include <iostream>
    #include <fstream>
    #include <string>
    using namespace std;
    
    class student
    {
    public:
    string name;
    
    int age;
    public:
    void grade() {
    
        int i = 0;
    
        //string name; 这里不要
    
        cout << "name:";
    
        cin >> name;
    
        cout << "age:";
    
        cin >> age;
    
        cout << "name:" << name << '\t' << "age:" << age << endl;
    
    }
    
    };
    int main() {
    student a[3];
    
    int i = 0;
    
    ofstream fout("c:\\text.txt");
    
    for (i; i < 3; i++) {
    
        a[i].grade();
    
    fout << "name:" << a[i].name << "age:" << a[i].age << endl;
    
    };
    
    fout.close();
    }
    
    
    

    问题解决的话,请点下采纳,谢谢合作

    点赞 打赏 评论

相关推荐 更多相似问题