How to copy contents of txt file into struct array
I have a text file named "student.txt" with 5 identity numbers and five names formatted like this.
p00001 DENNIS
p02302 ARRON
p04503 TOM
p30004 RYAN
p00003 DAVID
I want to create a structure with two member string variables.
string pNumber and string name.
I then want to create an array containing the 5 students and populate each element of the array with the contents of the students.txt file.
This is what I have to far. When I build and run it I get no output at all. Why is this the case?
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
|
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
struct Student
{
int pNumber;
int name;
};
int main()
{
Student classarray[5];
int count = 0;
ifstream infile;
infile.open("student.txt");
if (infile.fail())
{
cerr << "Error opening file " << endl;
exit(1);
}
while (!infile.eof())
{
infile >> classarray[count].pNumber >> classarray[count].name;
count++;
}
cout << "The Class List Is:\n";
cout << "pNUM\t\tNAME\n";
for (int i = 0; i < 5; i++)
{
cout << classarray[i].pNumber << " " << classarray[i].name << endl;
}
infile.close();
return 0;
}
|
Last edited on
> I want to create a structure with two member string variables.
> string pNumber and string name.
1 2 3 4 5
|
struct Student
{
int pNumber;
int name;
};
|
int != std::string
>
while (!infile.eof())
don't loop on eof, loop on the reading operation
1 2 3 4 5 6
|
std::string number, name;
while(infile>>number>>name){
classarray[count].pNumber = number;
classarray[count].name = name;
++count;
}
|
Topic archived. No new replies allowed.