0

scanf() always discards white spaces and new line characters. But when I give a character and press enter the new line character is read and stored. I'm unable to read required number of characters because of this. Is there any problem with my code, or some other thing?

The same problem goes with gets. Many posts suggested using fgets() rather than using the above both but I need to know why is this happening.

enter image description here

halfer
  • 19,824
  • 17
  • 99
  • 186
  • Please copy and paste the code instead co snapshots. – Shravan40 Jun 25 '17 at 06:31
  • Where are `n` and `m` declared? Also `char **str = malloc (sizeof *str * n);` and `str[row] = malloc (sizeof *str[row] * m);` (those are pointers, not the cause of your immediate issue). Please post [**A Minimal, Complete, and Verifiable example**](http://stackoverflow.com/help/mcve). `fflush (stdin)` is Undefined Behavior. – David C. Rankin Jun 25 '17 at 06:33
  • "scanf() always discards white spaces and new line characters"... Unless you use `%c` or `%[]` formats, which do not discard whitespace characters. You are using `%c`. – AnT stands with Russia Jun 25 '17 at 06:36
  • 1
    The `%c` format, which you are using, does not discard whitespace (including newlines, as they are a whitespace character). Also `fflush(stdin)` has undefined behaviour. If you want to purge pending input, find another approach. Lastly, try using some C++ streams rather than C I/O - they have several advantages, including reduced chance of buffer overrun (i.e. which is why C programmers recommend use of `fgets()`). – Peter Jun 25 '17 at 06:37
  • **note:** `main` is a function of `type int` and it returns a value. See [**See What should main() return in C and C++?**](http://stackoverflow.com/questions/204476/) – David C. Rankin Jun 25 '17 at 06:38
  • 1
    you code looks like C code, instead look at things like std::iostream and std::string it will make your life easier. – AndersK Jun 25 '17 at 06:45

1 Answers1

4

For %c the man page says (see http://man7.org/linux/man-pages/man3/scanf.3.html) :

c      Matches a sequence of characters whose length is specified by
       the maximum field width (default 1); the next pointer must be
       a pointer to char, and there must be enough room for all the
       characters (no terminating null byte is added).  The usual
       skip of leading white space is suppressed.  To skip white
       space first, use an explicit space in the format.

Notice the part: The usual skip of leading white space is suppressed.

Also Notice the part: To skip white space first, use an explicit space in the format.

So if you want to skip whites spaces, try adding a space before %c:

char c;
scanf(" %c", &c);
Support Ukraine
  • 42,271
  • 4
  • 38
  • 63