gpt4 book ai didi

C 编程 while 循环不要求输入

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

为什么 while 循环退出而不询问另一个值,即使在 for 循环中也没有设置另一个值。

#include<stdio.h>
int main(){
char another ='y';
int num = 0;
int i =0;
/*for(;another =='y'||another =='Y';i++){
scanf("%d",&num);
printf("%d",num);
printf("Enter another num?");
scanf("%c",&another);
}*/
while(another == 'y'|| another == 'Y'){
scanf("%d",&num);
printf("%d",num);
if(another == 'y'||another =='Y')
scanf("%c",&another);
}
return 1;
}

最佳答案

当您输入num时,它会留下换行符\n字符。第二个 scanf() 读取第一个 scanf() 留下的换行符。

因此,您的程序不会等待您的输入 another,因为它已经收到 \n 作为输入,这将导致您的 while 循环退出.

要解决此问题,请更改:

scanf("%c",&another);

致:

scanf(" %c",&another);

请注意,格式字符串中的前导空格“%c”将使scanf消耗换行符,从而解决您的问题。

引用此Answer了解更多此类场景。

关于C 编程 while 循环不要求输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48605310/

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