gpt4 book ai didi

c - 使用 while 循环在 C 中进行数据验证

转载 作者:行者123 更新时间:2023-11-30 16:49:20 25 4
gpt4 key购买 nike

#include<stdio.h>
main()
{
char status;
printf("STATUS SYMBOL\n");
printf("------ ------\n");
printf("Senior s\n");
printf("Junior j\n");
while(1)
{
printf("Please Enter the Salesperson's Status : ");
scanf("%c",&status);
if (status=='s' || status=='j')
{
if(status=='s')
{
printf("Weekly Salary is --- $400\n");
break;
}
else
{
printf("Weekly Salary is --- $275\n");
break;
}
}
else
{
printf("Please Enter a Valid Symbol!\n");

}
}
}

当输入无效数据时,该程序必须要求用户提供有效数据。While 循环用于验证数据执行两次,以便要求用户输入。为什么 scanf 函数在 First-Go 上被忽略?如何解决这个问题呢? Program Output

最佳答案

因为当您输入a<ENTER>时您输入 2 个字符。所以第一个 scanf 得到 a ,第二个得到 \n (输入)。

您可以更改 scanf 以获取 2 个字符而不是 1 个字符。

scanf("%c%c", &status, &newline);

关于c - 使用 while 循环在 C 中进行数据验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42613015/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com