String scanf用于字符串并与之一起使用

String scanf用于字符串并与之一起使用,string,if-statement,printf,scanf,String,If Statement,Printf,Scanf,我对C编程还是个新手,我一直在寻找解决方案,但没有找到。。 我试图要求用户输入字母c或f,并根据选择的字母进行正确的打印 #include <stdio.h> #include <conio.h> void startScreen(); char choice[1]; int main() { startScreen; _getch(); return 0; } void startScreen() { printf("Please

我对C编程还是个新手,我一直在寻找解决方案,但没有找到。。 我试图要求用户输入字母c或f,并根据选择的字母进行正确的打印

#include <stdio.h>
#include <conio.h>

void startScreen();
char choice[1];

int main()
{
    startScreen;
    _getch();
    return 0;
}

void startScreen()
{

    printf("Please choose c or f\n");
    scanf("%s", choice);
    if (choice[0] == 'f' || choice[0] == 'F')
        printf("Good choice");
    if (choice[0] == 'c' || choice[0] == 'C')
        printf("Good luck");
}
#包括
#包括
void startScreen();
字符选择[1];
int main()
{
startScreen;
_getch();
返回0;
}
void startScreen()
{
printf(“请选择c或f\n”);
scanf(“%s”,选项);
如果(选项[0]=“f”|选项[0]=“f”)
printf(“好选择”);
如果(选项[0]=“c”|选项[0]=“c”)
printf(“好运”);
}

谢谢你给我的帮助,谢谢

我的C已经很生疏了,但我想你遇到的问题是当你调用它并输入除“C”或“F”以外的内容时。看起来您需要修改startScreen()函数,如下所示:

void startScreen()
{
    printf("Please choose c or f\n");
    do {
      scanf("%s", choice);
      switch(choice[0]) {
         case 'f':
         case 'F':
           printf("Good choice");
           break;
         case 'c':
         case 'C':
           printf("Good luck");
           break;
         default:
           printf("Invalid input. Try again.");
       }
    } while (choice[0] != 'c' && choice[0] != 'C' && choice[0] != 'f' && choice[0] != 'F');
}

谢谢你们查德·埃斯特斯和艾哈迈德·阿布马莱克,我把你们两人所指的结合在一起,成功了

#include <stdio.h>
#include <conio.h>

void startScreen();

int main()
{
    startScreen();
    _getch();
    return 0;
}

void startScreen()
{
    char c;

    do 
    {
        scanf_s("%c", &c);
        switch (c) 
        {
        case 'f':
        case 'F':
            printf("Good choice");
            break;
        case 'c':
        case 'C':
            printf("Good luck!");
            break;
        default:
            printf("Invalid input. Try again.");
            break;
        }
    } 
    while (c != 'c' && c != 'C' && c != 'f' && c != 'F');
}
#包括
#包括
void startScreen();
int main()
{
startScreen();
_getch();
返回0;
}
void startScreen()
{
字符c;
做
{
scanf_s(“%c”和“&c”);
开关(c)
{
案例“f”:
案例“F”:
printf(“好选择”);
打破
案例“c”:
案例“C”:
祝你好运;
打破
违约:
printf(“输入无效。请重试”);
打破
}
} 
而(c!=“c”&&c!=“c”&&c!=“f”&&c!=“f”);
}

为什么要创建一个包含1个字符的全局数组
choice[1]
而不是简单地使用
char
变量?别忘了将此标记为答案,很高兴我们能提供帮助。明天可以根据规则这样做:)