0

So let's say I have a while loop that will end when the condition "isDone" is set to true. Inside the while loop, I ask the user to either enter an integer to continue the loop or a character to end it (by setting "isDone" to true).

How would I go about this using only one scanf()?

melpomene
  • 84,125
  • 8
  • 85
  • 148
L. Moore
  • 11
  • 1
  • 4
    You should not use `scanf` for user input at all. Use `fgets` or something like it instead. – melpomene Apr 09 '18 at 05:05
  • Take a look at `scanf`’s return value! – Ry- Apr 09 '18 at 05:07
  • 1
    You simply need to account for the `'\n'` that remains in the input buffer after integer input. Since leading *whitespace* is **NOT** discarded for the `%c` format specifier, you must remove the `'\n'` and any additional stray characters before attempting to read the `char`, e.g. `int c = getchar(); while (c != '\n' && c != EOF) c = getchar();` Then read your character. (and no you can't use the same `scanf`. Using `%d` will result in a *matching failure* for anything other than `[0-9]`) – David C. Rankin Apr 09 '18 at 05:11
  • Question unclear, need more exact spec for valid inputs and invalid inputs. What if user enters two non-integer characters for example, or integer and character? What about a decimal number? Two numbers? – hyde Apr 09 '18 at 05:21
  • Possible duplicate of [How to scanf only integer?](https://stackoverflow.com/questions/26583717/how-to-scanf-only-integer) – Pranav Totla Apr 09 '18 at 05:22
  • 1
    @DavidC.Rankin Or you could make the habit of tossing in an empty `getchar()` after each `scanf`, to chew up the line feed left in stdin. – Lundin Apr 09 '18 at 06:56
  • 1
    Well, you could, but that doesn't protect against the user doing something dumb like entering `43abc`, which `scanf ("%d", ...)` will convert `43` leaving `abc\n` in the input buffer. It's the old circular-firing-squad of `scanf` for mixed input problem -- doable, but each `I` and `T` must be dotted. – David C. Rankin Apr 09 '18 at 06:58
  • 1
    A solution is possible with `" %c%d"`, yet the amount of post processing is not even worthy of an academic exercise as compared to first reading with `fgets()`. – chux - Reinstate Monica Apr 09 '18 at 13:26

1 Answers1

5

The suggestion above is good advice: you're probably better off not using scanf() at all. It might be better to use something like fgets() instead, and then parse the string. Or even better, just use getchar().

But anyway ...

Remember that, in C, a "character" IS an integer. So just scanf("%c", &i) and check if you've got an "integer" (isdigit()) or a "character" (isalpha()).

paulsm4
  • 114,292
  • 17
  • 138
  • 190