Hi.
On Sep 8, 2012, at 11:41 PM, TianTian <syrttg...@gmail.com> wrote:
> Hi everyone, I am learning the chapter4. I meet the exercise 19. My question is how to write code to add values to two vectors: names and scores using the statement like while(cin >> temp)? Another question is how to end loop when meet the "NoName 0"? Thanks!
Since nobody else has responded ...
I don't have the book with me, so I don't know all the particulars of this exercise.int> scores. Based on your description, the following code does the job:
#include <bjarne/std_lib_facilities.h>
int main()
{
vector<string> names;
vector<int> scores;
cout << "Enter names and scores, terminate by \"NoName 0\":\n";
string the_name;
int the_score;
while (cin >> the_name >> the_score) {
if (the_name == "NoName" && the_score == 0)
break;
names.push_back(the_name);
scores.push_back(the_score);
}
cout << "\nYour input: \n\n";
for (int i = 0; i < names.size(); i++)
cout << names[i] << ": " << scores[i] << endl;
}
The while-guard has the added benefit of exiting the loop if there's an eof on cin, If you don't think that's a benefit, move the cin statement into the loop, and change the loop header to
while (true) {
Art Werschulz (8-{)} "Metaphors be with you." -- bumper sticker
GCS/M (GAT): d? -p+ c++ l u+(-) e--- m* s n+ h f g+ w+ t++ r- y?
Internet: agw STRUDEL comcast.net