getline with an input file using a function, array and structure

331 views Asked by At

I am writing a program for my class that takes a text file and has each line in the text assigned.The problem i am having is that when i use the getline() its completely skipping the input. From everything i have read i feel like i am doing it right but obviously i am missing something.This is a small part of the code...if you need the whole thing i can post it.Thanks ahead of time for everyone's help.

garage populategarage()
{
garage tg; //temporary garage
string instruction_prompt;

initialize_garage(tg);
ifstream inputFile;

inputFile.open("garage-input-file.txt");

for (int i = 0; i < NUM_OF_VEHICLES; i++)
{
    inputFile >> tg.vehicles[i].category;


    if (tg.vehicles[i].category == "\0")
        i = NUM_OF_VEHICLES;
    else
    {
        inputFile >> tg.vehicles[i].make;

        inputFile >> tg.vehicles[i].model;

        inputFile >> tg.vehicles[i].color;

        inputFile >> tg.vehicles[i].year;

        inputFile >> tg.vehicles[i].trans;

        inputFile >> tg.vehicles[i].cylinder;

        getline(inputFile, tg.vehicles[i].drive); //This is my problem

    }
}
1

There are 1 answers

0
paddy On

You haven't shown any example input, or what your results are, but from your description it seems like each value appears on its own line. Would that be right? In that case, the getline call is likely to be picking up the previous newline (from when you read cylinder), and returning an empty string.

If your values appear on separate lines, you should probably use getline for each. You can wrap this behaviour for any type into a template function - something simple like:

template <class T>
istream & readValue( istream & s, T & value )
{
    string line;
    if( getline( s, line ) )
    {
        istringstream iss( line );
        iss >> value;
    }
    return s;
}

If instead your file contains a single line for each entry, then it's usually better to use getline for the whole line, then read individual values from an istringstream.

for (int i = 0; i < NUM_OF_VEHICLES; i++)
{
    string line;
    if( !getline( inputFile, line ) ) break;
    istringstream iss( line );

    iss >> tg.vehicles[i].make;
    iss >> tg.vehicles[i].model;
    // etc...
}