Hi guys i'm kind of new to c programming so sorry if my question seems evident. When i use scanf("%c",c) it counts space as a character so what should i do to ignore the spaces between input characters? Any help would be much appreciated.
Asked
Active
Viewed 591 times
-2
-
add a space after the `%c` and it will escape that space sequence as follows `scanf("%c ", &c);` – iwrestledthebeartwice Nov 26 '21 at 16:46
-
3@iwrestledthebeartwice `scanf (" %c", &c);` - trailing whitespace in a *format-string* is never good. (or simply `int c; while ((c = getchar()) && c != EOF) { if(!isspace(c)) { /* do something with char */ }`) If taking user input you can add `.. && c != '\n' && ...` in your loop condition. – David C. Rankin Nov 26 '21 at 17:07
-
@iwrestledthebeartwice please see [What is the effect of trailing white space in a scanf() format string?](https://stackoverflow.com/questions/19499060/what-is-the-effect-of-trailing-white-space-in-a-scanf-format-string) – Weather Vane Nov 26 '21 at 17:29
-
Does this answer your question? [What is the effect of trailing white space in a scanf() format string?](https://stackoverflow.com/questions/19499060/what-is-the-effect-of-trailing-white-space-in-a-scanf-format-string) – Chris Turner Nov 26 '21 at 17:33
1 Answers
-6
The only thing you should do is to consider spaces as characters and scanning them like other characters. for example if you want to scan "a b" in characters, you should write
scanf("%c %c %c", &c1, &c2, &c3);
so that the space will be c2.

user438383
- 5,716
- 8
- 28
- 43

o.dl
- 8
-
1It is better to research how `scanf()` handles whitespace than kludging it. Format specifiers don't all behave the same way. The `scanf` conversion stops at the first character it cannot convert, which is typically (but not necessarily) a space or a newline, and that character remains in the input buffer. It will be read by the *next* `scanf()`. Format specifiers `%d` and `%s` and `%f` automatically filter such leading whitespace characters, but `%c` and `%[]` and `%n` do not. For those, you can instruct `scanf` to do so by adding a space just *before* the `%`. – Weather Vane Nov 26 '21 at 17:22
-
1The example is incorrect: The space in the input `"a b"` will be filtered by the space before the second `%c` in `"%c %c %c"` which will then read the `b` and there is no input provided for the third `%c`. To read each character of the input `"a b"` into three variables you need format spec `" %c%c%c"` – Weather Vane Nov 26 '21 at 17:25