1

I have to read stdin for two numbers separated by comma using standard C++ library (no boost). So user will be typing numbers in console in the format ,

Examples

2,3 3,10

If it was for C, I could do scanf("%d,%d", i, j); How do I do it in C++? cin be default uses space as separator, how do I change the separator for cin ?

fahadash
  • 3,133
  • 1
  • 30
  • 59
  • @JerryCoffin, those answers wont work in the case of spaces. – soandos Dec 19 '13 at 17:32
  • I like the [second](http://stackoverflow.com/a/3168809/645270) one. – keyser Dec 19 '13 at 17:33
  • 2
    You could read in a number, `cin.ignore(1, ',')`, read in the other number... –  Dec 19 '13 at 17:33
  • @soandos: He didn't ask about spaces, he asked about commas. In any case, my answer there will deal with spaces and/or commas (e.g., `1 , 2` will be read as just `1` and `2`). – Jerry Coffin Dec 19 '13 at 17:35
  • @JerryCoffin Reading from stdin, not string. – fahadash Dec 19 '13 at 17:36
  • @fahadash: And yet again: my answer there is actually reading from `std::cin`, but works equally well with any input stream. To use it with a string, you'd put the string into a stringstream. In any case, reading a string from a stream isn't exactly rocket science. – Jerry Coffin Dec 19 '13 at 17:39

1 Answers1

4

The approach I would use is to use a custom comma manipulator:

std::istream& comma(std::istream& in) {
    std::istream::sentry cerberos(in);
    if (cerberos) {
        if (in.peek() == ',') {
            in.ignore();
        }
        else {
            in.setstate(std::ios_base::failbit);
        }
    }
    return in;
}

You can then just inject comma where a comma should be read, e.g.:

int i, j;
if (in >> i >> comma >> j) {
    // process the data
}
Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380