File I/O

Nov 29, 2018 at 5:03pm
For my class, I am working on a project to read in a text file. I need to read the ID number, Name, and a list of numbers related to each name. I am having trouble figuring out how to store these numbers so that I can keep them as a record with the structure.

Example of text file:
2546 Hill, Mary
2 3 4 5 6 7 8
5487 Lee, Jill
1 2 3 4 5 6 7

My code:
void getFileInfo(Students student_info[])
{
ifstream inFile;

int i = 0;
inFile.open("guesses.txt");

if (!inFile)
cout << "\n\n **** ERROR OPENING FILE. ****\n" << endl;
else
{
while (!inFile.eof())
{
inFile >> student_info[i].id_num; //read ID
cout << student_info[i].id_num << endl;
inFile.getline(student_info[i].name, SIZE, '\n');
student_info[i].student_name = student_info[i].name;
//read numbers???
?????????????????

i++;
if (inFile.eof())
break;
}
}

inFile.close();
}
Nov 29, 2018 at 5:25pm
Do you know how many numbers will be associated with each name? Does every name have the same number of numbers as every other name?
Nov 29, 2018 at 5:34pm
7 numbers under each name!
Nov 29, 2018 at 5:37pm
Then I'd suggest adding an array of 7 ints to the Students structure, and storing the numbers there.
Nov 29, 2018 at 5:44pm
Perfect so how would I read those from the file to the array?
Nov 29, 2018 at 6:01pm
My array is essentially
int lotteryNumbers[7] = { 0 };

I'm not quite sure on how I should be reading the file to input the numbers into the array. That's where my biggest issue lies.
Nov 29, 2018 at 6:19pm
I'm not sure what the problem is. You clearly already know how to read multiple fields from a line into different variables, as you're already doing that for the lines with names in.

Can you be more specific about what's confusing you?

EDIT: http://www.cplusplus.com/doc/tutorial/basic_io/ might be worth a read, if you're having difficulties with I/O.
Last edited on Nov 29, 2018 at 6:20pm
Nov 29, 2018 at 6:50pm
I'm unsure of how to input the file into an int array. I used inFile to read a single integer. I used getline to read the names. I am unsure of how to read in the 7 numbers into an array from the file.
Nov 29, 2018 at 6:52pm
Just read each one in turn, using the << operator.

However, be aware that mixing stream I/O and getline can cause headaches; you need to ensure that you're not leaving endline characters on the stream.
Topic archived. No new replies allowed.