C program to read name and marital status of a girl and print her name with Miss or Mrs
C program to read name and marital status of a girl and print her name with Miss or Mrs
I need to make a C program to read name and marital status of a girl and print her name with Miss or Mrs.
It works fine with this code:
#include <stdio.h>
#include <string.h>
int main()
{
// Declare a char buffer to take input for name
char name[30]={0};
// Declare a char buffer to take input for answer
char YesNo[10]={0};
//input name
printf("Enter the name of a girl : ");
gets(name);
//input marital status
printf("Is the girl married (Y-Yes, N-No) : ");
gets(YesNo);
if((!strcmp(YesNo,"yes")) || (!strcmp(YesNo,"Y")))
printf("Her full name is : Mrs. %s",name);
else if((!strcmp(YesNo,"no")) || (!strcmp(YesNo,"N")))
printf("Her full name is : Miss %s",name);
else
printf("Marital status is wrong");
return 0;
}
But I want to know what is problem in this code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char name[100],mstatus=[30];
printf("Enter the name of the girl!n");
scanf("%c",&name);
printf("whether the girl is married (Enter 'Y' for Yes and 'N' for No)!n");
scanf("%c",&mstatus);
if(mstatus=='Y')
{
printf("Full name of girl is Mrs %c:",name);
}
else
{
printf("Full name of girl is Miss %c:",name);
}
return 0;
}
Why we only have to use gets
and not scanf
, and what is the use of strcmp
?
gets
scanf
strcmp
mstatus[0]
*mstatus
"what is the use of strcmp" its explained in the documentation, as well as all other lib functions are explained in there as well. Which version of the documentation did you read?
– alk
32 mins ago
Please note too that
gets
is obsolete. Why is the gets function so dangerous that it should not be used?– Weather Vane
26 mins ago
gets
In some circles, it would be best just to print "Ms" — though that can be a bit fraught too. Be wary of the social etiquette minefields into which this question is leading. (The coding problems are straight-forward — the socio-political ones are not.)
– Jonathan Leffler
4 mins ago
2 Answers
2
Here name is a string can contains more than one characters. So you must use %s format specifier to read it. It doesn't denote as a compilation error. It is a logical mistake. Also you can use strcmp() method for comparing two strings.
The problem with the second code is scanf() reads the string to variable name and leaves a newline character in the buffer. The second scanf reads only the 'n' character and ignores the value 'yes' or 'No'.
Having getchar() after the first scanf helps.
scanf("%s",&name);
getchar();
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
mstatus[0]
or*mstatus
- however you should use a debugger or print things out at least to attempt to debug stuff yourself. Also you don't mean %c, that's a single character– Salgar
37 mins ago