0

Why it has %s instead of %c?

#include <stdio.h>   
#include <conio.h>
    
void main()
{    
    clrscr();
    char fname[20], mname[20], lname[20];
    
    printf("Enter The First Name Middle Name & Last Name");
    scanf("%s %s %s",&fname, &mname, &lname);
    printf("Abbreviated name=%c. %c. %s", fname[0], mname[0], lname);
    
    getch();
}
Nup
  • 1
  • 3
  • Might I ask why you are using turbo C++? It is **VERY** old, and has not been updated since 2006. IMHO it should not be used anymore. Also, why are you using a C++ compiler for C code? – JHBonarius Jan 18 '22 at 10:34
  • Oh, and `void main()` is non standard and should not be used. It's illegal in C++. use `int main()` and `return EXIT_SUCCESS;` – JHBonarius Jan 18 '22 at 10:37
  • `%c` is for characters. `%s` is for strings. Characters and strings are *very* different. A character is not just a "short string". A character is not the same as a string of length 1. A string is an *array* of characters. You can't intermix the two. – Steve Summit Jan 18 '22 at 14:17

1 Answers1

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;
}
Sercan
  • 4,739
  • 3
  • 17
  • 36