【问题标题】:Program Ends Before Enter The Inputs(switch case) [duplicate]程序在输入输入之前结束(开关盒)[重复]
【发布时间】:2014-11-07 11:29:40
【问题描述】:

我是 C 编程新手 我写一个程序。但是当我在进入之前运行程序时,我的选择程序结束了。 这是屏幕截图。 https://onedrive.live.com/download?resid=E63780628DD96583!3161&authkey=!APl3ReO7T4XIO_s&v=3&ithint=photo,jpg

#include<stdio.h>
#include<conio.h>
main()
{
    char ch;
    int num1, num2, a, m, s;
    float d;
    printf("\nEnter The First Number: ");
    scanf("%d", &num1);
    printf("\nEnter The Second Number: ");
    scanf("%d", &num2);
    a=num1+num2;
    m=num1*num2;
    s=num1-num2;
    d=(float)(num1/num2);
    printf("\nEnter Your Choice: ");
    scanf("%c", &ch);
    switch(ch)
        {
            case 'A': printf("\nThe Addition Of The Number Is= %d", a);
                break;
            case 'M': printf("\nThe Multipication Of The Numbers Is= %d", m);
                break;
            case 'S': printf("\The Subsraction Of THe Numbers Is= %d", s);
                break;
            case 'D': printf("\nThe Division Of The Two Numbers Is= %f", d);
                break;
            default : printf("\nInvalid Entry");
                break;
        }
    getch();
    return 0;
}

我在哪里做错了???

【问题讨论】:

  • 不调试你的程序将是第一个错误。没有对scanf() 进行研究以了解它确实不在读取没有空格前导码的格式化单个%c 时跳过空格,因此在第二个数字之后消耗你的换行符而不是你想要的字符成为第二个错误。
  • 为什么是纯文本输入输出的屏幕截图?无论如何,您也只检查大写字母。我敢打赌你没有在大写锁定的情况下打字,所以你输入的是小写字符。

标签: c switch-statement


【解决方案1】:

在scanf 中的%c 之前添加一个空格将解决此问题。这是因为scanf 在输入前两个整数的值后不会消耗\n 字符。作为Enter 键( \n) 也是一个字符,它被 scanf("%c",&amp;ch); 消耗,因此,您的默认情况被执行。%c 之前的空格将丢弃所有空格和空格。

【讨论】:

  • 谢谢。有用。但是为什么???
  • 看这里:en.cppreference.com/w/c/io/fscanf“格式字符串中的任何单个空白字符都会消耗输入中所有可用的连续空白字符”
  • 如果有两个"\n"。那么,我应该在 scanf 中的 "%c" 之前给出双空格吗????
  • @MaxySpark ,阅读我回答的最后一句话。一个空格将丢弃所有个空格。
  • 谢谢@Cool Guy,你是主角!!! ? :)
猜你喜欢
  • 1970-01-01
  • 2012-11-12
  • 1970-01-01
  • 1970-01-01
  • 2016-10-05
  • 2022-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多