用C语言进行字符串输入

用C语言进行字符串输入,c,C,我想从用户(字符串)获取输入。但是,我想限制用户只输入三种类型,然后继续程序。否则,如果输入了任何其他字符串,我希望打印无效。我写了一个程序,但肯定不行 #include <stdio.h> int main() { char hotel[100], first, second, third; printf("Enter Your Choice: "); scanf("%s", &hotel); if (hotel != first &

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

#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");
    }
}
#包括
int main()
{
查尔酒店[100],第一、第二、第三;
printf(“输入您的选择:”);
scanf(“%s”和酒店);
如果(酒店!=第一家酒店!=第二家酒店!=第三家酒店){
printf(“无效!”);
}否则{
printf(“OK”);
}
}
这应该可以完成工作(查看注释以获得解释):

#包括
#包括/*以使用strcmp*/
int main(int argc,char*argv[]){
查尔酒店[100];
/*您需要初始化这些字符串并使用正确的类型(char*或char[])*/
const char*first=“first”;
const char*second=“second”;
const char*third=“third”;
printf(“输入您的选择:”);
scanf(“%s”,hotel);/*格式指定类型“char*”,但参数的类型为“char(*)[100]”[-Wformat]=>删除“&”*/
/*注意:使用FGET而不是scanf更安全*/
/*使用strcmp比较字符串*/
如果(strcmp(酒店,第一)!=0和strcmp(酒店,第二)!=0和strcmp(酒店,第三)!=0){
printf(“无效!”);
return 1;/*主函数应返回一个整数值(如果成功,则返回0)*/
}否则{
printf(“OK”);
返回0;/*主函数应返回整数值(如果成功,则返回0)*/
}
} 

您必须输入换行符。a)
首先
etc是错误的类型。b) 他们没有经验。c) 您必须将c中的字符串与strcmp进行比较,而不是与
=
进行比较=。请查看编译器的警告,并查看如何更正。切勿将
scanf()
与纯
%s
(无宽度说明符)一起使用。不要放弃结果。你应该有
if(scanf(“%99s”,hotel)!=1){fputs(“Input error!”,stderr);exit(exit_FAILURE);}
在那里。你可能想稳妥一点:
scanf(“%s”,hotel)
=>
if(scanf(“%99s”,hotel)!=1{printf(“意外的文件结尾”\n”);返回1;}
@chqrlie或使用
fgets
代替我在评论中的建议:)
fgets()
但是不能直接替代
scanf(“%s”,…)
fgets()
将读取完整(但可能为空)包含尾随换行符(如果有)的行,而
scanf()
将跳过包括换行符在内的初始空白,并读取第一个字,在标准输入缓冲区中保留任何后续的空白分隔符。非常不同的语义。
#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) */
    }
}