1

I m new in c programing I write a program. But when i run the program before i entered my choice program ends. Here is the screenshot. 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;
}

Where Did I Do The Mistake???

Alex Reynolds
  • 95,983
  • 54
  • 240
  • 345
MaxySpark
  • 555
  • 2
  • 10
  • 26
  • Not debugging your program would be the first mistake. Not doing research on [`scanf()`](http://en.cppreference.com/w/c/io/fscanf) to understand it does *not* skip whitespace when reading a formatted single `%c` with no whitespace preamble and thus is consuming your newline after the second number rather than the character you desire would be the second mistake. – WhozCraig Sep 13 '14 at 11:17
  • 1
    Why a screen shot of plain text input and output? Anyway, you are also checking for capitals only. I bet you don't type with caps lock on, so you are entering *lowercase* characters. – Jongware Sep 13 '14 at 11:56

1 Answers1

3

Add a space before %c in the scanf will solve the issue.This happens because scanf does not consume the \n character after you enter the values of the first two integers.As the Enter key(\n) is also a character,it gets consumed by the scanf("%c",&ch); and thus,your default case gets executed.The space before the %c will discard all blanks and spaces.

Spikatrix
  • 20,225
  • 7
  • 37
  • 83