C程序:使用标准输入scanf函数读取字符时出错 [英] C Program :Error when reading character from stdin using scanf
问题描述
目前我试着去学习简单的C程序。但是,我来到了这个情况:
Currently im trying to learn simple C Programs. 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();
}
}
该计划是好的,当用户第一次输入的字符。并且,当它要求继续。而且,用户输入1那么它的行为weired。它会自动输入空白字符和打印的ASCII和GOTO一样的地方。
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. It automatically input blank character and prints the ascii and goto the same place.
我该如何解决?而且,特别是,为什么这样做的原因?
How can i resolve this? And, specially, Why is the reason for this?
和,对不起我的英语不好!
And, Im sorry about my poor english!
感谢您提前。
推荐答案
的问题是,你正在阅读的第二个scanf的单号,但用户输入的多单数出现,用户还输入了新行字符由pressing。
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 .
用户输入1 \\ N。您的scanf的读1,而忽略了\\ n个输入流。那么接下来scanf函数读取字符从流中读取\\ n。
User enters "1\n". Your scanf reads "1", leaving out "\n" in the input stream. Then the next scanf that reads a character reads "\n" from the stream.
下面是更正后的code。我用的getc放弃额外的新行字符是存在的。
Here is the corrected code. I use getc to discard the extra new line character that is there.
#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);
}
}
此外,作为一个侧面说明,您可以使用 CONIO.H
这不是标准C的一部分,它是MS-DOS的头文件,因此它不是可移植的C你是写作。我从code删除它,但你可能希望保留它。
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. I have removed it from my code, but you might wish to keep it.
这篇关于C程序:使用标准输入scanf函数读取字符时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!