1
votes

Will scanf skip white space characters before reading non-white space characters or any other data with all the the format specifiers like %d , %c , %s and all the other format specifiers.I am talking about the first occurrences of white space characters and not the subsequent ones. for example,

#include<stdio.h>
#define N 10
int main(void){
char str[N];
scanf("%s",str);
return 0;
}

In this case scanf will skip first occurrences of white space characters and read the next non-white space data and then if it again encounters white space characters , it will quit reading.

2
The code won't compile; str has an incomplete type. You need to specify an array size.Jonathan Leffler
@JonathanLeffler i corrected that.chanzerre
OP returns 13 months later to make a pointless edit... +1 for styleM.M

2 Answers

3
votes

Most of the scanf() format specifiers automatically skip leading white space. White space includes newlines — see isspace().

The three exceptions are %c, scansets (%[a-z] etc), and %n.

Note that any white space in a scanf() format string is an explicit indication to skip optional white space. That is, if there is white space, it will be skipped; if the next character is not white space, there is no white space to skip but no error either.


The POSIX page for isspace() misses out some of the information in the C standard:

The standard white-space characters are the following: space (' '), form feed ('\f'), new-line ('\n'), carriage return ('\r'), horizontal tab ('\t'), and vertical tab ('\v'). In the "C" locale, isspace returns true only for the standard white-space characters.

0
votes

If you want read the white space before the non-white space, you may need fgets

#include <stdio.h>

int main()
{
        char n[10];
        fgets(n,10,stdin);
        printf("%s",n);
}

Run the program:

   343  5   <<--Input
   343  5   <<--Output