-1

I am reading some numbers. The input is for example:

1 2 3 4 ; 2 3 4 5 6;

When I read ';' I want to do something with it and the number up to it. Currently, I am using:

while(1) {
    cin >> num;
    if(cin.fail()){
        // end of first array
        return 0;
    }
}

However, this way cin may fail if it is any char, not just ';'

Karina Kozarova
  • 1,145
  • 3
  • 14
  • 29
  • 2
    [`std::getline`](http://en.cppreference.com/w/cpp/string/basic_string/getline) along with `std::istringstream` will let you do what you want – Justin Nov 27 '17 at 19:18
  • If `std::cin` is in fail state the next character to read will be a `';'` in your example, and you can use `clear()` and consume the `';' character to continue`. – user0042 Nov 27 '17 at 19:19
  • 2
    Take a look at option 2 in this answer: https://stackoverflow.com/a/7868998/4581301 . Take advantage of the ability to specify the end of line token (`while (std::getline(infile, line, ';'))`) and replace the file stream with `cin`. – user4581301 Nov 27 '17 at 19:21

1 Answers1

0

You can read cahr and check it. If it isn't a digit, do what you want and return; else put the char back using cin.putback(char) and read int.

 char c;
 while (1) {
     cin >> c;
     if (c < '0' || c >'9') { // is not digit
         // do something
         return 0;
     }
     cin.putback(c);
     cin >> num;
 }
hant0508
  • 528
  • 1
  • 9
  • 19