C++ homework question

So the first section of code is working you can ignore that.
The problem im having is the second section where im trying to read the text file into my array of structures. It's outputting the right thing the first time through, and then it starts spitting out a bunch of random shit the last 3 times through. Thanks in advance for any help you can give!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include "ConsoleApplication36.h"
using namespace std;
// define structure studentInfo
struct studentInfo
{
	char name[20];
	int age;
	float gpa;
	char grade;
};
int main()
{
	//create array of structures
	studentInfo student[4] =
	{ { "Ann Annson", 10, 1.10, 'D' },
	{ "Bill Billson", 20, 2.20, 'C'},
	{ "Carl Carlson", 30, 3.30, 'B'},
	{"Don Donson", 40, 4.40, 'A' } };


	studentInfo studentsText[4];
	studentInfo studentsBinary[4];


	fstream dataFile;

	dataFile.open("B:\\students.txt", ios::out);

	for (int i = 0; i < 4; i++)
	{
		dataFile << student[i].name << "\n"; //writing line 1, name
		dataFile << student[i].age << "\n";  // writing line 2, age
		dataFile << student[i].gpa << "\n";  // line 3, gpa
		dataFile << student[i].grade << "\n"; // line 4, grade
	}
	dataFile.close();
	string input;
	dataFile.open("B:\\students.txt", ios::in);
	if (dataFile)
	{
		int i = 0;
		while(dataFile)
		{
			dataFile.getline(studentsText[i].name, 20);
			dataFile >> studentsText[i].age;
			dataFile >> studentsText[i].gpa;
			dataFile >> studentsText[i].grade;
			i++;
		}
	}
	for (int i = 0; i < 4; i++)
	{
		cout << studentsText[i].name << endl;
		cout << studentsText[i].age << endl;
		cout << studentsText[i].gpa << endl;
		cout << studentsText[i].grade << endl;
	}
    return 0;
}
Something like this - not tested.
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
        int i = 0;
        while (i < 4 && dataFile) // don't exceed array bounds
        {
            dataFile.getline(studentsText[i].name, 20);
            dataFile >> studentsText[i].age;
            dataFile >> studentsText[i].gpa;
            dataFile >> studentsText[i].grade;
            if (dataFile) // increment count only if file access was successful
                i++;
            dataFile.ignore(); // remove trailing newline 
        }

	for (int n = 0; n < i; n++) // loop actual number of records read.
	{
		cout << studentsText[n].name << endl;
		cout << studentsText[n].age << endl;
		cout << studentsText[n].gpa << endl;
		cout << studentsText[n].grade << endl;
	}    

Last edited on
Topic archived. No new replies allowed.