c - 输入一个字母,存储在一个变量中将字母打印到命令行

标签 c visual-studio-2010 variables user-input windows-7-x64

我正在尝试制作一个非常基本的程序来比较 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/

相关文章:

c# - free memory 不清除内存块

visual-studio-2010 - 无法在表单属性菜单下拉菜单中从 'WaitCursor' 切换

c# - Reportviewer 报表过滤器 - 检查日期是否为空

将未初始化的局部变量传递给函数时出现 C++ 编译器警告(?)

c - char* 变量中的垃圾值

c - 编译C文件和汇编文件时出现链接错误

c# - 如何评估即时窗口中未处理的异常属性

php - 关于 PHP 中的作用域和 OOP

bash - 使用具有各种引号级别和空格的变量构建命令字符串

c - HDF-EOS 配置失败, "C compiler cannot create executables"