0

Say I have user input these variables: ID name age

And I'm using a while loop to get user input like below

while(cin){

cin >> ID >> name >> age;

do_stuff(ID, name, age);



}

but if at some moment the user only input some of those variables, say only ID and name, the while loop should end immediately without running do_stuff(). How should I do this, the method needs to be fast. Thank you!

4

2 回答 2

1
#include <iostream>
#include <string>
int main() {
        int ID, age;
        std::string name;
        while(std::cin.good()){
                if (std::cin >> ID && std::cin >> name && std::cin >> age) {
                        std::cout << ID << name << age << std::endl;
                }

        }
        return 0;
}
于 2013-03-31T00:32:36.613 回答
0

You can achieve this by using stringstream and getline, something like the following:

  #include <sstream>
  #include <string>

  int age = -1; //assume you init age  as -1 and age is integer type
  stringstream ss;
  while (getline(cin,line))
  {
     age = -1;
     ss.clear();
     ss << line;
     ss >> ID >> name >>age;

    if (age ==-1)  //if no age is parsed from input line, break the while loop
    {
       cout << "no age is contained in input line" <<endl;
       break;
    }
    do_stuff(ID,name, age)
  }

This should work, but there may exist better solution.

于 2013-03-31T00:27:17.177 回答