0

Is there a way in c++ to perform formatted input in C-like way (with scanf %d %s %f and others)? I need to read a double, for example, and I would really like my program not to brake if user accidentally inputs some letters or other non-digits.

Forgot to mention: I need this without using scanf

GaussGun
  • 100
  • 1
  • 9
  • 2
    [`std::scanf`](https://en.cppreference.com/w/cpp/io/c/fscanf)? – Drew Dormann Oct 05 '21 at 21:31
  • Not sure what you're after here. If you want C-Style input, use the C functions. – user4581301 Oct 05 '21 at 21:31
  • How to do this in a more idiomatic style: [Good input validation loop using cin - C++](https://stackoverflow.com/questions/2075898/good-input-validation-loop-using-cin-c) – user4581301 Oct 05 '21 at 21:33
  • Some ideas here (maybe duplicate): [The easiest way to read formatted input in C++?](https://stackoverflow.com/q/11374617/10077) – Fred Larson Oct 05 '21 at 21:33
  • 1
    `Is there a way` yes. What have you tried? What research did you do? Why using `double d; std::cin >> d` is not a solution for you? Both `scanf` and `std::cin::operator>>` use _exactly_ the same methods for extracting the string, the standard even provides [equivalents](https://eel.is/c++draft/locale.num.get) of one to other. – KamilCuk Oct 05 '21 at 21:38
  • @FredLarson this is about strings. I need it mostly for numeric types. – GaussGun Oct 05 '21 at 21:38
  • @KamilCuk well it does fine until you try to input a non-digit symbol. Only way i found to fix it is adding `fflush(stdin)` after `cin`. – GaussGun Oct 05 '21 at 21:41
  • @GaussGun: There are `char`s, `string`s and `int`s there. You're not doing anything they're not. – Fred Larson Oct 05 '21 at 21:41
  • 1
    `fflush(stdin)` is invalid - it's undefined behavior, do not use it. No, one and only way to fix is to handle errors. `if (!(std::cin >> doubleval)) { std::cout << "Och no, you inputted invalid input. Ignoring the whole line\n"; std::cin.ignore(...::max, '\n'); }`. It's exactly the same as in C - `if (scanf("%f", &doubleval) != 1) { printf(...); while ((c = getchar()) != EOF && c != '\n'); }`, there's no difference in logic. – KamilCuk Oct 05 '21 at 21:41
  • @KamilCuk Thanks, that works. I didn't remember having this problem in C and somehow didn't find post mentioned in one of comments above, so I decided to ask. Maybe I was doing something wrong. – GaussGun Oct 05 '21 at 21:54

0 Answers0