C程序读取一个女孩的姓名和婚姻状况并打印她的名字与小姐或夫人

标签 c

我需要编写一个 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/

相关文章:

CUDA __constant__ 对全局内存的尊重。哪个缓存?

c++ - 这是 C/C++ 中的未定义行为吗

c - 读一段c语言

c - free() 使代码崩溃

c - C 源代码的标记化输出

java - JNI make 文件不起作用。多重定义

c - 程序运行不佳(意味着输出(printf))但在 gdb t.exe 中运行良好

c - 对多种类型使用 qsort()

mysql - 多行sql求和;

c - 从 getchar 切换到 fgets