关于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没有被记录下来?

c++

1个回答

因为你又定义了一个叫做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();
}


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

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问