1

I've been trying to write a program that asks at end of the calculation if we wish to exit it based on input provided. But if I input n, it waits for another input for it to exit the program and after the second input it exits. Is there any way to avoid this? And also the reason why this happens. Here is the complete code.

#include<stdio.h>

int main()
{ 
    float num1, num2;
    char op, cont;
    while(1)
    {
        scanf(" %f %c %f",&num1,&op,&num2);


        if (op=='+')
            printf("%.3f \n",num1+num2);
        else if(op=='-')
            printf("%.3f \n",num1-num2);
        else if(op=='*')
            printf("%.3f \n",num1*num2);
        else if(op=='/')
        {
            if(num2==0)
                printf("Look where you put your zeroes\n");
            else
                printf("%.3f\n",num1/num2);
        }
        else if(op=='%')
            printf("%d\n",(int)num1%(int)num2);
        else 
        {
            printf("What was the crap you just entered?\n");
        }

        printf("Continue using calc?[y/n]");
        scanf(" %c\n",&cont);
        if (cont=='n')
            break;
    }

    return 0;
}
Parnab Sanyal
  • 749
  • 5
  • 19
  • try using `cont=getchar();` instead of `scanf(" %c\n", &cont);` – Imran Ali Sep 24 '16 at 07:13
  • no doubt that `\n` is causing that problem.. – Parnab Sanyal Sep 24 '16 at 07:15
  • Yeah @ParnabSanyal that worked! Thanks man. Also any idea why that happened? Because I input y it seems to be working just fine. – Krishna Chaitanya Sep 24 '16 at 07:18
  • No. @KrishnaChaitanya. It just seems like it is working fine. But It is not. – Parnab Sanyal Sep 24 '16 at 07:25
  • 2
    Do not put trailing white space, not even a newline, in a `scanf)` format string. Any white space (such as a blank, tab or newline) in the format string skips zero or more white space characters, not stopping until it comes across a character that's not white space, or EOF. That means it keeps reading until you type something that isn't white space. You have to predict what the next input needs to start with to stop the current one. That's nasty for your users! The leading blank before the `%c` is good; the trailing newline is awful! Drop it. The code will work sanely. – Jonathan Leffler Sep 24 '16 at 07:36

3 Answers3

0

Detailed explanation :Simple C scanf does not work?

Community
  • 1
  • 1
hashdefine
  • 346
  • 2
  • 5
0

After the following changes I have your program working:

char op, cont='y';
while(cont == 'y')

scanf(" %c", &cont);
Imran Ali
  • 2,223
  • 2
  • 28
  • 41
0

The problem occured because of the last scanf. For excuting first scanf for num1 op num2 it requires a return (Enter) and after that while executing scanf for char count it takes that last retun key (Enter) as input .. So again it asks for num1 op num2 . this can be stopped by many ways , to stop it via scanf use "scanf(℅c℅*c,&count)" .%*c will ignore that return key input.