在 C 语言中,如何验证一个字符串变量是否等于一个不是变量的特定字符串? (不比较两个字符串)
How can I verify if one string variable is equal to a specific string that is not a variable in a do while in C language?? (not compare two strings)
我已经阅读了 C 字符串函数手册页。我发现的最好的东西是“strcmp”和“strncmp”。但这不是我想要的,因为它比较两个字符串。我只是想比较这样的...
char input[3];
do {
//important code
printf ("You want to continue??);
fflush(stdin);
gets(input);
} while (input == "yes" || "Yes);
没用。我不需要使用字符串,而只需要使用一个字符,例如:“y”表示是。有什么办法可以做我想做的事吗?我怎样才能将这一个字符串与这些值进行比较?
这里我写了一个简单的解决方案来满足你想要实现的目标。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char input[4];
do {
printf ("You want to continue??");
fflush(stdin);
gets(input);
} while (strcmp(input, "yes") == 0 || strcmp(input, "Yes") == 0);
return 0;
}
如果要进行字符串比较,使用strcmp
。您将根据需要只比较一个变量,但具有两个不同的值。换行:
while (input == "yes" || "Yes");
至:
while ( strcmp(input,"yes") == 0 || strcmp(input, "Yes") == 0);
此外,更改:
char input[3];
至:
char input[4];
因为您需要考虑终止 [=15=]
字符。
您很可能会 运行 换行符
到下一个输入。这是一个解决方案。
#include <stdio.h>
#include <stdlib.h>
int
main(void)
{
char input[4], garbage[50];
do
{
//important code
printf ("You want to continue??");
scanf("%s", input);
fgets(garbage, sizeof(garbage), stdin); //Newline char is now stored into garbage.
} while (strcmp(input,"yes") == 0 || strcmp(input,"Yes") == 0 );
return 0;
}
我已经阅读了 C 字符串函数手册页。我发现的最好的东西是“strcmp”和“strncmp”。但这不是我想要的,因为它比较两个字符串。我只是想比较这样的...
char input[3];
do {
//important code
printf ("You want to continue??);
fflush(stdin);
gets(input);
} while (input == "yes" || "Yes);
没用。我不需要使用字符串,而只需要使用一个字符,例如:“y”表示是。有什么办法可以做我想做的事吗?我怎样才能将这一个字符串与这些值进行比较?
这里我写了一个简单的解决方案来满足你想要实现的目标。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char input[4];
do {
printf ("You want to continue??");
fflush(stdin);
gets(input);
} while (strcmp(input, "yes") == 0 || strcmp(input, "Yes") == 0);
return 0;
}
如果要进行字符串比较,使用strcmp
。您将根据需要只比较一个变量,但具有两个不同的值。换行:
while (input == "yes" || "Yes");
至:
while ( strcmp(input,"yes") == 0 || strcmp(input, "Yes") == 0);
此外,更改:
char input[3];
至:
char input[4];
因为您需要考虑终止 [=15=]
字符。
您很可能会 运行 换行符 到下一个输入。这是一个解决方案。
#include <stdio.h>
#include <stdlib.h>
int
main(void)
{
char input[4], garbage[50];
do
{
//important code
printf ("You want to continue??");
scanf("%s", input);
fgets(garbage, sizeof(garbage), stdin); //Newline char is now stored into garbage.
} while (strcmp(input,"yes") == 0 || strcmp(input,"Yes") == 0 );
return 0;
}