我想从用户(字符串)获取输入。但是,我想限制用户只输入三种类型,然后继续执行该程序。否则,如果输入了任何其他字符串,我想打印无效。我写了一个程序,但它肯定行不通。

#include <stdio.h>

int main()
{
    char hotel[100], first, second, third;

    printf("Enter Your Choice: ");
    scanf("%s", &hotel);

    if (hotel != first && hotel != second && hotel != third) {
        printf("Invalid!");
    } else {
        printf("OK");
    }
}

最佳答案

这应该可以完成工作(请看注释以获取解释):

#include <stdio.h>
#include <string.h> /* to use strcmp */

int main(int argc, char *argv[]) {
    char hotel[100];

    /* You need to initialize those strings and use the right type (char* or char[]) */
    const char *first = "first";
    const char *second = "second";
    const char *third = "third" ;

    printf("Enter Your Choice: ");
    scanf("%s", hotel); /* format specifies type 'char *' but the argument has type 'char (*)[100]' [-Wformat] => remove the '&' */
    /* Note: using fgets instead of scanf is safer */

    /* Use strcmp to compare strings */
    if (strcmp(hotel, first) != 0 && strcmp(hotel, second) != 0 && strcmp(hotel, third) != 0) {
        printf("Invalid!");
        return 1; /* Your main function should return an integer value (0 if success) */
    } else {
        printf("OK");
        return 0; /* Your main function should return an integer value (0 if success) */
    }
}

10-04 12:45
查看更多