[英]C Program :Error when reading character from stdin using scanf
Currently im trying to learn simple C Programs. 目前,我正在尝试学习简单的C程序。 But, i came into this situation : 但是,我遇到了这种情况:
#include<conio.h>
#include<stdio.h>
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();
}
}
The program is fine when user first enter a character. 用户首次输入字符时,该程序很好。 And, when it ask to continue. 并且,当它要求继续时。 And, user enter 1 then it is behaving weired. 并且,用户输入1则表示异常。 It automatically input blank character and prints the ascii and goto the same place. 它会自动输入空白字符并在同一位置打印ascii和go。
How can i resolve this? 我该如何解决? And, specially, Why is the reason for this? 尤其是为什么呢?
And, Im sorry about my poor english! 而且,我为我的英语不好对不起!
Thank you in Advance. 先感谢您。
When you use 使用时
scanf("%d",&tryagain);
the number is read into tryagain
but the newline character, '\\n'
, is still left on the input stream. 该数字将tryagain
读取,但换行符'\\n'
仍保留在输入流中。 The next time you use: 下次使用时:
scanf("%c",&c);
the newline character is read into the c
. 换行符读入c
。
By using 通过使用
scanf("%d%*c",&tryagain);
the newline is read from the input stream but it is not stored anywhere. 从输入流中读取换行符,但未将其存储在任何地方。 It is simply discarded. 它只是被丢弃。
The issue is that you are reading a single number in the second scanf, but user inputs more than a single number there, the user also input a new line character by pressing . 问题是您在第二个scanf中正在读取单个数字,但是用户在那里输入了多个数字,用户还可以通过按输入新的换行符。
User enters "1\\n". 用户输入“ 1 \\ n”。 Your scanf reads "1", leaving out "\\n" in the input stream. 您的scanf读取为“ 1”,在输入流中忽略了“ \\ n”。 Then the next scanf that reads a character reads "\\n" from the stream. 然后,下一个读取字符的scanf从流中读取“ \\ n”。
Here is the corrected code. 这是更正的代码。 I use getc to discard the extra new line character that is there. 我使用getc放弃了那里多余的换行符。
#include <stdio.h>
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 %d\n", 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);
}
}
Also, as a side note, you use conio.h
which is not part of standard C, it's MS-DOS header file, thus it's not portable C you are writing. 另外,请注意,您使用的conio.h
不是标准C的一部分,它是MS-DOS头文件,因此您编写的不是可移植的C。 I have removed it from my code, but you might wish to keep it. 我已将其从代码中删除,但您可能希望保留它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.