0

I wrote this simple addition software, in which I wanted the addition to end when the user entered 'n'. My current code works just fine. But I made two more variations of the same code, one worked, and one gave me an error. Can anyone tell me what is happening exactly in each case?

int a, b=0;
    cout<<"Welcome to my Addition Software!!\n\n";
    do{
        cin>>a;
        b+=a;
    }while(getchar()!='n');
    cout<<b;
    //works just fine
    int a, b=0;
    cout<<"Welcome to my Addition Software!!\n\n";
    do{
        fflush(stdin);
        cin>>a;
        b+=a;
    }while(getchar()!='n');
    cout<<b;
    //this one works too
int a, b=0;
    cout<<"Welcome to my Addition Software!!\n\n";
    do{
        a=getchar();
        b+=a;
    }while(a!='n');
    cout<<b;
    //doesn't work

I wanna know why fflush(stdin) have no effect on the code. If I just keep writing my input like "20, 30, 50, n" instead of "20, y, 30, y, 50, n" I get the same result in both working codes. Why does this happen?

1 Answers1

0

First of all, it is best to use C++ standard input and output std::cin and std::cout respectively.

The main problem with your code is that it conflicts with types you want:

You want to add integers int together and to see if the input is the character char 'n'.

What's happening is the legacy C fflush(stdin) "flushes" or clears the standard input stream buffer (read more here: https://www.google.com/amp/s/www.geeksforgeeks.org/use-fflushstdin-c/amp/) and getchar() receives character input from the user. getchar() returns a character and by deduction, your code transmutes that input into its integral int ASCII-ANSI numerical integral equivalent.

This means that on the third version, when you input "30", what actually is collected is '3' and without flushing the buffer, the next input is considered '0' causing a problem.

I suggest you use a control structure to check if the user wants to continue before receiving input to add:

int a = 0, b =0;
char c = 0; // for y/n responses
std::cout << "Welcome to my ... "; //just finish this string
do{
std::cout << "input integer: "; // for better formatting leave at least one space after the colon
std::cin >> a;
b += a;
std::cout << "Continue? n to stop: "
std::cin >> c;
} while (c != 'n')
std::cout << "Added: " << b;
  • Thanks. Can you explain about the other two? Would be very grateful. And the thing is, I want to omit the y/n structure. – Death Zark Nov 07 '19 at 00:27