Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does space in scanf mean? [duplicate]

Tags:

c

scanf

#include <stdio.h>
int main(int argc, char* argv[]) {
  char c;
  scanf(" %c", &c);
  printf("%c\n", c);
  return 0;
}

[root@test]# ./scanf 
a
a

[root@test]# ./scanf 
 h
h

It seems always matching whether space exists,why?

like image 415
Je Rog Avatar asked Jul 05 '11 12:07

Je Rog


People also ask

What does space do in scanf?

Space in scanf format means "skip all whitespace" from the current position on. Since most scanf format specifier will already skip all whitespace before attempting to read anything, space is not used in scanf format most of the time.

Does %s read whitespace?

When you use scanf with %s it reads until it hits whitespace. To read the entire line you may want to consider using fgets().

Why is there a space before %C in scanf?

Space before %c removes any white space (blanks, tabs, or newlines). It means %c without space will read white sapce like new line(\n), spaces(' ') or tabs(\t). By adding space before %c, we are skipping this and reading only the char given.

Does scanf skip spaces?

The value of ch2 is ',' and that is not too surprising either. It is likely that you might expect the value of ch3 to be '1', since that is the next visible character on the input line, but notice that scanf does not skip white space when it is reading character data, as it does when it reads numeric values.


1 Answers

The %c will not skip whitespace char as numeric format specifiers do. So if you use :

#include<stdio.h>
int main(int argc, char* argv[]){
  char c;
  scanf("%c", &c);
  printf("%c\n", c);
  scanf("%c", &c); // Try running with and without space
  printf("%c\n", c);
  return 0;
}

It is very likely that the previous whitespace character in the input buffer will be taken in the second scanf, and you will not get a chance to type. The space before %c will make scanf skip whatever whitespace character is there in the input buffer so that you will be able to enter your input properly. Sometimes to get the same effect people write:

fflush(stdin);
scanf("%c" &c);

But this is considered very bad programming as C Standard specifies the behavior of fflush(stdin) is undefined. So always use space in the format string unless you have a specific reason to capture whitespacesas well.

like image 154
Codebuddy Avatar answered Sep 20 '22 17:09

Codebuddy