我有一个简单的程序,但我遗漏了一些东西,因为当它比较输入的字符串时,它总是不等于0.
我的代码:
#include <stdio.h>
#include <string.h>
int main()
{
int loop = 1;
char response[9];
char *Response;
printf("Enter a string: ");
while(loop = 1)
{
scanf("%s", &response);
Response = response;
if(strcmp(Response,"Random") != 0 || strcmp(Response,"Database") != 0 || strcmp (Response,"Both") != 0)
printf("\n\"%s\" is an invalid entry. Valid responses are: \"Random\", \"Database\", or \"Both\": ", Response);
else
break;
}
printf("\nYour string is: %s\n", Response);
return 0;
}
当我输入“Random”,“Database”或“Both”时,它仍然认为该字符串无效。请帮忙。谢谢!
答案 0 :(得分:3)
改为:
#include <stdio.h>
#include <string.h>
int main()
{
int loop = 1;
char response[9];
char *Response;
printf("Enter a string: ");
while(loop = 1)
{
scanf("%s", &response);
Response = response;
if(strcmp(Response,"Random") == 0 || strcmp(Response,"Database") ==0 || strcmp (Response,"Both") ==0 ){
//correct response
break;
}else{
printf("\n\"%s\" is an invalid entry. Valid responses are: \"Random\", \"Database\", or \"Both\": ", Response);
}
}
printf("\nYour string is: %s\n", Response);
return 0;
}
<强>输出强>
Sukhvir@Sukhvir-PC ~
$ ./test
Enter a string: sdjkfjskfjaskd
"sdjkfjskfjaskd" is an invalid entry. Valid responses are: "Random", "Database", or "Both": Both
Your string is: Both
Sukhvir@Sukhvir-PC ~
$ ./test
Enter a string: Both
Your string is: Both
答案 1 :(得分:2)
您正在测试字符串是不是“随机”,还是“数据库”,或者不是“两者”。
假设它是'随机':它肯定不是'数据库',所以你报告它是无效的。
将||
替换为&&
。
答案 2 :(得分:2)
如果用户输入Random
,则会获得:
strcmp(Response, "Random") != 0
=&gt; 0 strcmp(Response, "Database") != 0
=&gt; 1 strcmp(Response, "Both") != 0
=&gt; 1 自(0 || 1 || 1) => 1
起,您的if
成功并打印错误消息。
您需要将比较与和连接,而不是或。
if(strcmp(Response,"Random") != 0 && strcmp(Response,"Database") != 0 && strcmp(Response,"Both") != 0)
然后(0 && 1 && 1) => 0
,if
不会打印错误消息。
答案 3 :(得分:-1)
使用strncmp:
if(strncmp(str,“test”,4)== 0){printf(“it matches!”); }
使用此链接了解有关此内容的更多信息