First, please do some basic research before coming here - questions like this can usually be answered with a quick Google search or checking your handy C reference manual.
char inputChar; // stores a single character
char inputString[100] = {0}; // stores a string up to 99 characters long
scanf( " %c", &inputChar ); // read the next non-whitespace character into inputChar
// ^ Note & operator in expression
scanf( "%s", inputString ); // read the next *sequence* of non-whitespace characters into inputString
// ^ Note no & operator in expression
You would use %c
when you want to read a single character from the input stream and store it to a char
object. The %c
conversion specifier will not skip over any leading whitespace, so if you want to read the next non-whitespace character, you need a blank before the %c
specifier in your format string, as shown above.
You would use %s
when you want to read a sequence of non-whitespace characters from the input stream and store them to an array of char
. Your target array must be large enough to store the input string plus a terminating 0-valued character. The %s
conversion specifier skips over any leading whitespace and stops reading at the first whitespace character following the non-whitespace characters.
Both %c
and %s
expect their corresponding argument to have type char *
(pointer to char
); however, in the first case, it's assumed that the pointer points to a single object, whereas in the second case, it's assumed that the pointer points to the first element of an array. For inputChar
, we must use the unary &
operator to obtain the pointer value. For inputString
, we don't, because under most circumstances an expression of type "array of T
" will be converted ("decay") to an expression of type "pointer to T
", and the value of the expression will be the address of the first element of the array.
Your code works fine as it is, but it's a bit confusing to read a single character and store it to an array.
Using %s
without an explicit field width is risky; if someone types in more than 100 non-whitespace characters, scanf
will happily store those extra characters to memory following inputString
, potentially clobbering something important. It's generally safer to write something like
scanf( "%99s", inputString ); // reads no more than 99 characters into inputString
or to use fgets()
to read input strings instead:
fgets( inputString, sizeof inputString, stdin );
Please check §7.21.6.2 of the online draft of the C language standard for a complete description of all of the conversion specifiers for the *scanf
functions.