C编程while循环不要求输入

时间:2018-02-04 06:12:33

标签: c scanf

为什么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;
    }

2 个答案:

答案 0 :(得分:0)

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

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

要解决此问题,请更改:

scanf("%c",&another);

要:

scanf(" %c",&another);

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

有关此类情况,请参阅此Answer

答案 1 :(得分:0)

只需在scanf()行之前输入fflush(stdin)。并包含stdlib.h头文件。

相关问题