如何修复输出?

时间:2017-04-26 02:13:08

标签: c++

基本上所有这个程序所做的都是将数据读入student_type的结构数组中,并且所有print_students函数都输出数据,我得到的主要是正确的输出,但我也得到随机的大数字。文件数据包含以下信息和我的代码如下我如何修复我的输出?

Smith
John
123456
3.4
J
1750.4
302
Fairmont St NW
Washington
DC
20059
Smitty
Frank
78910
2.7
F
1940.7
302
Sixth St SW
Washington
DC
20059
#include <iostream> 
#include <string> 
#include <fstream>
using namespace std;
struct Address_type

{
    int street_no;
    string street_name;
    string city;
    string state;
    int zip;
};
struct student_type
{
    string lname;
    string fname;
    int ID;
    float GPA;
    char classification;
    float account_balance;
    Address_type student_address;
};
void print_students(student_type[]); // prototypein
int main()
{
    ifstream myfile;
    student_type students[5];
    myfile.open("infile.txt");
    string name1, name2, name3;

    for (int i = 0; i < 2; i++) {
        myfile >> students[i].lname;
        myfile >> students[i].fname;
        myfile >> students[i].ID;
        myfile >> students[i].GPA;
        myfile >> students[i].classification;
        myfile >> students[i].account_balance;
        myfile >> students[i].student_address.street_no;
        myfile >> name1 >> name2 >> name3;
        students[i].student_address.street_name = name1 + " " + name2 + " " + name3;
        myfile >> students[i].student_address.city;
        myfile >> students[i].student_address.state;
        myfile >> students[i].student_address.zip;
        print_students(students);
    }
    myfile.close();
}
void print_students(student_type students[])
{
    for (int i = 0; i < 2; i++) {
        cout << students[i].lname << endl;;
        cout<< students[i].fname<<endl;
        cout<< students[i].ID<<endl;
        cout<< students[i].GPA<<endl;
        cout<< students[i].classification<<endl;
        cout<< students[i].account_balance<<endl;
        cout<< students[i].student_address.street_no<<endl;
        cout<<students[i].student_address.street_name<<endl;
        cout << students[i].student_address.city << endl;
        cout << students[i].student_address.state << endl;
        cout << students[i].student_address.zip << endl;
    }
}

1 个答案:

答案 0 :(得分:0)

看起来您在循环的第一次迭代中打印了所有学生数据。你应该等到你加载了所有数据为止。

此外,在C ++中,使用标准库容器非常重要,并且在这样的情况下尽量避免使用C风格的固定长度数组,以便从未知长度的文件中读取

这是用这个:

std::vector<student_type> students;

可以在正确撰写的push_back记录中添加student_type之类的内容。

然后你可以通过引用传递它,例如print_students。现在,无论出于何种原因,你只是假设该数组中有三个条目(长度为5?)并继续将其转储出去,即使它没有被填充。< / p>