我需要编写一个 C 程序来读取一个女孩的姓名和婚姻状况,并打印出她的名字“小姐”或“夫人”
使用此代码可以正常工作:
#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;
}
但是我想知道这段代码有什么问题:
#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;
}
为什么我们只需要使用gets
而不使用scanf
,以及strcmp
有什么用?
最佳答案
这里的名称是一个字符串,可以包含多个字符。所以你必须使用%s格式说明符来读取它。因此,在使用 scanf 读取字符串时,可以免除使用解引用运算符来获取 ir 的地址。你只要传递它的名字就足够了。它并不表示编译错误。这是一个逻辑错误。您也可以使用 strcmp() 方法来比较两个字符串。
关于C程序读取一个女孩的姓名和婚姻状况并打印她的名字与小姐或夫人,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51124713/