gpt4 book ai didi

c - 每次输入一个单词,这个单词的字母数量就会在c中打印很多次的错误信息

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

对从哪里开始解决这个问题有点困惑。例如,如果我运行该程序,当它要求输入正数时,我会输入“kobe”,错误消息将显示4次,“我很抱歉......”等等。

 #include<stdio.h>

int main(int agrc, char * argv[]) {
int sum = 0, num, c;
printf("Please enter a positive integer: \n");
scanf_s("%d", &num);
scanf_s("%c", &c);

do
{
sum = num;
if (num <= 0) {
printf("I'm sorry, you must enter an integer greater than zero: \n");
scanf_s("%d", &num);
scanf_s("%c", &c);
}

} while (num <= 0);

printf("The positive integer was: %d\n", sum);

return 0;
}

最佳答案

检查scanf_s的返回值以确保输入操作确实成功(即用户输入了十进制整数):

num = 0;
while ( num <= 0 )
{
printf("Please enter a positive integer: \n");
if ( scanf_s( "%d", &num ) == 0 )
{
/**
* A return value of 0 means the user typed in something
* that isn't a decimal integer; clear out the input
* stream and try again.
*/
while ( getchar() != '\n' )
; // empty loop
}
}

关于c - 每次输入一个单词,这个单词的字母数量就会在c中打印很多次的错误信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32784267/

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