gpt4 book ai didi

c - 如何使用 while 循环不断请求输入,直到输入正确 (C)?

转载 作者:太空宇宙 更新时间:2023-11-04 00:11:15 25 4
gpt4 key购买 nike

<分区>

我想使用一个 while 循环来不断询问用户正确的输入,直到给出为止。这可以用 scanf() 实现吗?我知道,如果输入不匹配,它就会保持未分配状态,并被保存以供第二个 scanf() 捕获。

下面的程序永远运行,并且在第一个输入错误时不会询问我的第二个输入。

#include<stdio.h> 
/* Check the input, if the input does not contain a single integer value,
then keep asking for the integer value */
/* I used a counter variable so that the program does not run on forever */
int
main (int argc, char * argv[]){
int counter = 10, items = 0, input = 0;
while (counter){
printf("input an integer value: ");
items = scanf("%d",&input);
if (items == 1){
printf("successfully read an item");
break;
}
else{
counter --;
input = 0;
printf("failed to read an item, please try again\n");
}
}
return 0;
}

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