-
push_back problem
I have a file that contains names and grades. It looks like this
Mike 60
Joe 25
Steve 80
...
This file is opened inside a function. Here is the function:
Code:
void Bag_of_Grades::input_file ()
{
ifstream grades_stream ;
grades_stream.open ( "D://C++//notes//streams_data1.dat" ) ;
string name;
int score;
while ( grades_stream >> name >> score)
{
grades.push_back ( name );
}
}
This function works, but in only passes the name into the vector (grades)
I tried alot of stuff including:
Code:
grades.push_back ( name , score );
or
grades.push_back ( name );
grades.push_back ( score );
or
grades.push_back ( name >> score);
But I can't get this right
How can I pass the name and the score to the vector ?
-
Aye, you can't push an int into a vector of strings. Sounds like you want a vector of structs, each struct containing a name and a score. Alternately, if you knew that each name was unique, you could use a map of strings to ints.
-
im no whizz but ive just never seen this, what does it do, and is it correct?
Code:
while ( grades_stream >> name >> score)
how did you define your grades, maybe it can only hold strings the way you declared it.
thats my input
-
grades_stream is an input stream object (much like cin, only on this case an ifstream). It is simply reading the value of the stream after an attempt to retrieve a string(name), followed by a space, followed by an int (score).
If that particular format is not present on the next reading iteration (for instance it would contain "nadroj user", where "user" is obviously not an int), the the stream will return false and the reading loop will end.
-
>> what does it do, and is it correct?
It is correct, and usually the best alternative to using while (!eof()).
-
It is correct and it "transfers" the elements from the grade_stream into name and score.
for example "Mike" goes into name and 60 goes into "score"
PS. I made it a vector of struct and it works, thanks for the tip pianorain