scanf函数不会要求输入第二次 [英] scanf won't ask for input the second time

查看:194
本文介绍了scanf函数不会要求输入第二次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include "stdio.h"

int main(void)
{

     int order, nextp, N=3;
     char cont;
     nextp = 0;
     printf("\nShould we continue (y or n): ");
     scanf("%c", &cont);
     if (cont != 'y') return;
     for(; nextp < N; nextp++)
     {
        printf("Enter order number: ");
        scanf("%d", &order);
        printf("you have entered %d\n", order);
        printf("okay now continue with cont\n");


        printf("enter cont y or n: ");
        scanf("%c", &cont);
        if (cont != 'y')
        {
            printf("\nnot equal to y\n");
            break;
        }
        printf("after intepreting t[0]");
      }

   return 0;
}

输出看起来像这样

The output looks like this

Should we continue (y or n): y
Enter order number: 45
you have entered 45
okay now continue with cont
enter cont y or n: 
not equal to y

第二个输入被跳过。为什么呢?

The second input was skipped. Why?

推荐答案

,这种情况正在发生。

because of newline character already in stdin , this is happening. use

scanf(" %c", &cont); 

而不是

scanf("%c", &cont);

请注意%C前一个空格。

note one space before %c.

这篇关于scanf函数不会要求输入第二次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆