When to use %s instead of %c? [duplicate]
Solution 1:
If the %s
format specifier is used with the scanf()
function, it is intended to read data from stdin to a char
pointer. If the %s
format specifier is used with the printf()
function, it writes to stdout the characters that a char
pointer represents in memory (up to the '\0'
character).
There is an error in the use of the scanf()
method because the name of the arrays is also the address of the array. In the example below, the format specifier %s
is used in the scanf()
method when reading data from stdin
, since fname
, mname
, and lname
are char
pointers. Since fname[0]
and mname[0]
are char
data, the format specifier %c
was used when printing to stdin. Because lname
is a char
pointer, the format specifier %s
was used when printing to stdout.
#include<stdio.h>
int main()
{
char fname[20], mname[20], lname[20];
printf("Enter The First Name Middle Name & Last Name");
// The error in the line below has been fixed.
scanf("%s %s %s",fname, mname, lname);
printf("Abbreviated name=%c. %c. %s", fname[0], mname[0], lname);
return 0;
}