c/c++语言开发共享C程序:使用scanf从stdin读取字符时出错

目前我正在尝试学习简单的C程序。 但是,我遇到了这种情况:

#include #include void main() { char c; int tryagain=1; while(tryagain>0){ printf("Enter the Character : "); scanf("%c",&c); printf("You entered the character "%c" and the ascii value is %d",c,c); getch(); clrscr(); tryagain=0; printf("You want to Trry again Press 1 : "); scanf("%d",&tryagain); clrscr(); } } 

用户首次输入角色时程序正常。 并且,当它要求继续时。 并且,用户输入1然后它表现为weired。 它会自动输入空白字符并打印ascii并转到同一个地方。

我怎么解决这个问题? 而且,特别是,为什么这样的原因?

而且,对不起我的英语很差!

先感谢您。

    问题是您正在读取第二个scanf中的单个数字,但是用户输入的数字不止一个,用户也可以通过按下输入新的行字符。

    用户输入“1 n”。 您的scanf读取“1”,在输入流中省略“ n”。 然后,读取字符的下一个scanf从流中读取“ n”。

    这是更正后的代码。 我使用getc来丢弃那里的额外新行字符。

     #include  void main() { char c; int tryagain = 1; while (tryagain > 0) { printf("Enter a character: "); scanf("%c", &c); printf("You entered the character "%c" and the ascii value is %dn", c, c); tryagain = 0; printf("If you want to try again, enter 1: "); scanf("%d", &tryagain); // get rid of the extra new line character getc(stdin); } } 

    另外,作为旁注,你使用conio.h ,它不是标准C的一部分,它是MS-DOS头文件,因此它不是你正在写的便携式C. 我已将其从代码中删除,但您可能希望保留它。

    当你使用

     scanf("%d",&tryagain); 

    该数字被读入tryagain但新行字符'n'仍留在输入流中。 下次使用时:

     scanf("%c",&c); 

    换行符被读入c

    通过使用

     scanf("%d%*c",&tryagain); 

    从输入流中读取换行符,但不会将其存储在任何位置。 它被简单地丢弃了。

      以上就是c/c++开发分享C程序:使用scanf从stdin读取字符时出错相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/c-cdevelopment/549534.html

      (0)
      上一篇 2021年1月14日
      下一篇 2021年1月14日

      精彩推荐