Dave Lea
Dave Lea

Reputation: 11

Issue reading multiple lines from .txt file in C++

I'm trying to create a student database system for a school project. I'm trying to create a function that will search a .txt file for the student id and return all of the other variables on the string. This is working great if I search for the id of the student on the first line of the txt file but isn't capturing anything if I search for a student on another line. Am I missing something obvious?

The student data is 16 strings delimited by commas on each line. The student ID is the first string.

Thanks for any assistance!

StudentType findStudent(int studentToFind)
{
    ifstream inFile;
    inFile.open("students.txt");

    string currentLine;
    string dataRead[16];
    istringstream is;
    int currentStudent;

    if (inFile)
    {
        while (getline(inFile, currentLine))
        {
            is.str(currentLine);

            for (int i = 0; i < 16; i++)
            {
                getline(is, dataRead[i], ',');
            }

            currentStudent = stoi(dataRead[0]);

            if (currentStudent == studentToFind)
            {
                /*
                 Do stuff here
                */

                inFile.close();
                return foundStudent;
            }
            cin.ignore(); // Not sure if this is needed but I was trying to 
                          // clear the \n char if that was causing the issue
        }
    }
}

Upvotes: 0

Views: 1684

Answers (1)

UpAndAdam
UpAndAdam

Reputation: 5467

First : you aren't using cin, so get rid of cin.ignore().

Second : you should make sure you ALWAYS close infile at the end... so I would suggest not returning early or closing early, but using a break statement to exit your loop and then have a single return of whether you found it or not.

Third: Now that you removed all the 'gorp' we can finally hone in on the problem ... effectively the question is do we read all the lines?

Well let's check that, try printing out currentLine each time at the beginning of the while loop, if you know currentLine is updated properly, is is getting updated each time? yes...

ok then look at your next loop let's print out currentStudent each time... does currentStudent print the right value for each line? i.e. is the getline write into dataRead[i] actually writing what you think it should be to the right space?

Did you find the problem yet?

This is the kind of problem you need to learn how to solve yourself using print statements and a debugger. That what its for. If you are in visual studio run in debug mode and step through it... if not, use gdb. learn it and get used to it, you'll be using it a lot!

good luck

Upvotes: 3

Related Questions