如何根据输入打印不同的字符串?
How to print different strings depending on the input?
我希望在输入姓名 Emily 或 Jack 时显示一条消息,而另一条输入则显示一条不同的消息。
我的代码:
#include <stdio.h>
#include <string.h>
int main()
{
char name;
printf("What is your name?");
gets(name);
if ((strcmp(name,"Emily") == 0) || (strcmp(name,"Jack") == 0))
{
printf("Hello %s\n", name);
} else
{
printf("Welcome Stranger!\n");
}
return 0;
}
此代码可以编译但不会输出任何内容。
第一个问题是 name
只能存储一个 char
,要存储一串字符,您需要一个 char
数组。
第二个问题,不是导致错误行为但同样重要的是 gets
的使用。此函数已在 C99 中弃用,并从 C11 的国际标准中删除,并且有充分的理由,它非常危险,因为它很容易溢出目标缓冲区,它无法控制输入流的长度。 fgets
经常被使用。
char name[256]; //array store the name
//...
fgets(name, sizeof name, stdin); //safe, can't overflow the buffer, input size is limited
name[strcspn(name, "\n")] = '[=10=]'; //fgets parses the newline character, it must be removed
//...
我希望在输入姓名 Emily 或 Jack 时显示一条消息,而另一条输入则显示一条不同的消息。
我的代码:
#include <stdio.h>
#include <string.h>
int main()
{
char name;
printf("What is your name?");
gets(name);
if ((strcmp(name,"Emily") == 0) || (strcmp(name,"Jack") == 0))
{
printf("Hello %s\n", name);
} else
{
printf("Welcome Stranger!\n");
}
return 0;
}
此代码可以编译但不会输出任何内容。
第一个问题是 name
只能存储一个 char
,要存储一串字符,您需要一个 char
数组。
第二个问题,不是导致错误行为但同样重要的是 gets
的使用。此函数已在 C99 中弃用,并从 C11 的国际标准中删除,并且有充分的理由,它非常危险,因为它很容易溢出目标缓冲区,它无法控制输入流的长度。 fgets
经常被使用。
char name[256]; //array store the name
//...
fgets(name, sizeof name, stdin); //safe, can't overflow the buffer, input size is limited
name[strcspn(name, "\n")] = '[=10=]'; //fgets parses the newline character, it must be removed
//...