今天用c语言测试,做了两个c小文件
主.c
#include<conio.h>
void testing();
int main()
{
testing();
getch();
return 0;
}
测试.c
#include <stdio.h>
void testing()
{
char ch;
printf("Hello Testing\n");
do{
printf("Enter Character : ");
ch=getchar();
printf("You Entered : %c\n",ch);
testing();
}while(ch!='N');
}
我面临的问题是它从用户那里读取一个字符然后循环两次,我不知道为什么
output
Hello Testing
Enter Character : k //(i entered k)
You Entered : k
Hello Testing// why this is displayed twice??
Enter Character : You Entered :// i don't press any key and it moves to next iteration
Hello Testing
Enter Character : // here i can enter character again and it happens again twice
我已经在 Visual Studio 2012 上编译了它。
最佳答案
因为 getchar()
在输入缓冲区中留下了一个换行符。您可以使用另一个 getchar() 来吃掉换行符。
ch=getchar();
getchar();
或者使用 scanf 吃掉前导空格:
scanf(" %c", &ch);
这样所有之前的\n
都会被忽略。
关于c函数调用错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12977620/