0

Is there a way to "delete" all the newline characters stuck in the buffer from previous reading before asking the user for a new character? Right now I'm doing it like this

scanf("%c ", &trash);
scanf("%c", &input);
scanf("%c", &trash);

and although it works, it seems very inefficient and inelegant. Suggestions?

1 Answers1

2

When using the %c format specifier, which will match any character including whitespace, you typically want to put a space in the format string before %c. This will absorb any number of whitespace characters.

scanf(" %c", &input);
dbush
  • 205,898
  • 23
  • 218
  • 273
  • 1
    yeah, but this is an ultra classic dupe. You've seen that a lot of times. So why answering? – Jean-François Fabre Jan 30 '19 at 21:04
  • what if I want to absorb the whitespace that is generated after the user inputs the next char? Should I add a space even after %c? –  Jan 30 '19 at 21:06
  • or use `fgets` because `scanf` sucks – Jean-François Fabre Jan 30 '19 at 21:07
  • 1
    @FoxyIT You don't want it after, otherwise the current `scanf` won't return until you enter a non-whitespace character. Just put a space before a `%c`. Other format specifiers such as `%s` and `%d` do this implicitly, so no need to add a space before those. – dbush Jan 30 '19 at 21:07
  • @dbush the newline from the first char does get stuck in the next %s scan call tho, that's why I'm having problems ahah –  Jan 30 '19 at 21:11
  • 1
    @FoxyIT It shouldn't. If it is, you're doing something else wrong. – dbush Jan 30 '19 at 21:12
  • Right. `%s` always skips any leading whitespace, including newlines. Be careful, though, for the format `" %c"` skips *all* whitespace until it reads a non-whitespace character. This includes possibly many newlines, and also leading spaces, tabs, etc. on the line that provides the character that is ultimately returned. This may or may not be what you actually want. – John Bollinger Jan 30 '19 at 21:16
  • @dbush oh yeah, found where the problem is :) Is there any way to absorb the newline char and whitespace with getchar or can I only use the scanf method you told me? –  Jan 30 '19 at 21:17
  • 3
    @FoxyIT `getchar` only reads one character at a time. You could do it that way, but then you'd have to explicitly loop and check for each character you don't want. If you're already using `scanf` then stick with it. Also, don't mix `scanf` with `fgets` or `getline` as they handle whitespace differently. – dbush Jan 30 '19 at 21:18
  • And if you were forced to choose between one of the aforementioned functions, `fgets` is the way to go – Govind Parmar Jan 30 '19 at 21:30