Why Does This While Loop...

ToneZ1

Beta member
Messages
5
Just by looking, hopefully this can be resolved, because i have about 4 different user-defined classes that i would need to post up if need be. please help, I need to know why this while loop only passes once:

while (getline (cast, name, '\n'))
{
cast >> age;
cast >> junk;
Person* newCharacter = new Person (name, age);
fromFile.push_back(newCharacter);

}


age is int.
junk is string.
name is string.
cast is fstream (input).
fromfile is a vector <*Person> (person is a user defined class).
newCharacter is a Person.


please help. Again, I will post the classes if needed.


edit: oh yes, this is in C++, everyone.
 
The while loop
Its format is:

while (expression) statement

and its functionality is simply to repeat statement while the condition set in expression is true.

It stops after one cycle because "getline (cast,name, '\n'))" becomes untrue. Usually you see integers as the expression, not functions.
 
alright, the text file looks like this...


1st Name
1st Age
2nd Name
2nd Age


the "while" condition in the parens gets the first name, then goes down and gets the first age. then takes the white space after the input operator and stores that to junk. then takes the first name and age and puts that to a new Person pointer and puts that on the backend of a Vector. The while isn't false rite now because it is here:


First Name
First Age
Second Name <~~ HERE
Second Age


although it is there (or should be there), it ends the loop automatically. The while condition isn't false because there is more text document to input as the condition is true, but it automatically stops. That's my problem, can anyone see an error?
 
Just by looking, hopefully this can be resolved, because i have about 4 different user-defined classes that i would need to post up if need be. please help, I need to know why this while loop only passes once:

Code:
while (getline (cast, name, '\n'))
        {
                cast >> age;
                cast >> junk;
                Person* newCharacter = new Person (name, age);
                fromFile.push_back(newCharacter);

        }

age is int.
junk is string.
name is string.
cast is fstream (input).
fromfile is a vector <*Person> (person is a user defined class).
newCharacter is a Person.


please help. Again, I will post the classes if needed.


edit: oh yes, this is in C++, everyone.
Try adding
Code:
cast.ignore();
here,
Code:
while (getline (cast, name, '\n'))
        {
                cast >> age;
                cast >> junk;
                Person* newCharacter = new Person (name, age);
                fromFile.push_back(newCharacter);

                cast.ignore();//< -- here

        }
If that helps then use your favorite search engine with the phrase "mixing cin and getline". Then post back with any questions.
 
Back
Top Bottom