Home > front end >  Program does not print two strings given by the user
Program does not print two strings given by the user

Time:11-18

The compiler does not print when I use more than one scanf function and stops after getting the inputs from user:

#include <stdio.h>
int main()

{
   char firstName, lastName [20];
  
   //get first name from user
   printf("Your first name:");
   scanf("%s", &firstName);
   
   //get last name from user
   printf("Your last name:");
   scanf("%s", &lastName);
   
   //print the full name of the user
   printf("Your full name is: %s %s", firstName, lastName);
}

But a similar code with only one scanf function works perfectly fine:

#include <stdio.h>
int main()

{
   char firstName [20];
  
   //get first name from user
   printf("Your first name:");
   scanf("%s", &firstName);
   
   //print the full name of the user
   printf("Your name is: %s %s", firstName);
}

I don't know how to handle this problem. Tried using different online compilers but I had the same error each time.

CodePudding user response:

There is a typo in this declaration

char firstName, lastName [20];

the identifier firstName has the scalar type char.

It seems you mean

char firstName[20], lastName [20];

Or to avoid such a typo you could introduce a typedef alias for the array type as for example

typedef char CArray20[20];

and then write

CArray20 firstName, lastName;

Also you should write at least like

scanf("%s", firstName);

and

scanf("%s", lastName);

instead of

scanf("%s", &firstName);

and

scanf("%s", &lastName);

Though it will be more safer to write

scanf("s", firstName);

and

scanf("s", lastName);

CodePudding user response:

You are not initialising firstName like lastName . You can either use malloc or initialise it like you do with lastName

  • Related