比较字符串输入与另一个字符串

时间:2013-10-24 04:11:59

标签: c string scanf

我有一个简单的程序,但我遗漏了一些东西,因为当它比较输入的字符串时,它总是不等于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”时,它仍然认为该字符串无效。请帮忙。谢谢!

4 个答案:

答案 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) => 0if不会打印错误消息。

答案 3 :(得分:-1)

使用strncmp:

if(strncmp(str,“test”,4)== 0){printf(“it matches!”); }

使用此链接了解有关此内容的更多信息

http://www.cplusplus.com/reference/cstring/strncmp/