我正在尝试制作一个非常基本的程序来比较 2 个数字。输入 2 个数字后,系统会询问用户是否要比较这 2 个数字。如果 y/n 表示是或否。我遇到的问题是程序似乎没有要求我输入并立即转到下一个打印语句。这是代码:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int main(void){
int n1;
int n2;
char ch;
printf("compare 2 numbers, input a number\n");
scanf("%d", &n1);
printf("your first number is %d\n", n1);
printf("enter your second number to compare \n");
scanf("%d", &n2);
printf("your second number is %d\n", n2);
printf("do you want to compare these numbers? y/n \n");
//here is the problem. after entering y, the program closes.
//at this point I just want it to print the letter it was given by the user.
scanf("%c", &ch);
//the print statement that is supposed to print the letter the user inputs
printf("%c is a vowel.\n", ch);
getch();
return 0;
}
//我使用这段代码作为正确运行的引用
#include <stdio.h>
int main()
{
char ch;
printf("Enter a character\n");
scanf("%c", &ch);
if (ch == 'a' || ch == 'A' || ch == 'e' || ch == 'E' || ch == 'i' || ch == 'I'
|| ch =='o' || ch=='O' || ch == 'u' || ch == 'U')
printf("%c is a vowel.\n", ch);
else
printf("%c is not a vowel.\n", ch);
return 0;
}
最佳答案
当你做的时候
printf("enter your second number to compare \n");
scanf("%d", &n2);
您将输入第二个数字并按 ENTER
。此 ENTER (\n)
仍在缓冲区中。
scanf
函数会自动删除空格。当您使用 %c
时,scanf()
将新行字符留在缓冲区中(%c
是异常(exception),它们不会删除 空格
).
scanf("%c", &ch);
而不是这个用途
scanf("\n%c", &ch);
关于c - 输入一个字母,存储在一个变量中将字母打印到命令行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20367770/