0

我有一个简单的程序,但我遗漏了一些东西,因为当它比较输入的字符串时,它总是不等于 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

4 回答 4

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
于 2013-10-24T04:15:00.223 回答
2

您正在测试字符串是否不是“随机”、不是“数据库”或不是“两者”。

假设它是“随机的”:它肯定不是“数据库”,所以你报告它是无效的。

替换||&&

于 2013-10-24T04:15:18.960 回答
2

如果用户输入Random,那么你会得到:

  • strcmp(Response, "Random") != 0=> 0
  • strcmp(Response, "Database") != 0=> 1
  • strcmp(Response, "Both") != 0=> 1

由于(0 || 1 || 1) => 1,您if成功并打印了错误消息。

您需要将比较与and、 not or联系起来。

if(strcmp(Response,"Random") != 0 && strcmp(Response,"Database") != 0 && strcmp(Response,"Both") != 0)

然后(0 && 1 && 1) => 0,并且if不打印错误消息。

于 2013-10-24T04:15:52.907 回答
-1

使用 strncmp:

if (strncmp(str, "test", 4) == 0) { printf("匹配!"); }

使用此链接了解更多信息

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

于 2013-10-24T04:17:02.093 回答