0

I am a noob to C++, and as a part of homework I had to create a simple calculator with four functions within C++. I have done this and it works, however, I am now trying to loop it so that a user can have infinite attempts at using it, however, I am having struggles. Basically, when I run my program and tell the program which operation I'd like to use, it tells me that my variable "sum" is not being initialized. Im not quite sure what this is, or how to fix it. Any ideas? Here is my code -

#include "stdafx.h"
#include <iostream>
using namespace std;
int main() 
{

    while (true)
    {
        int num1, num2, r;
        double sum;

        cout << "Enter a number\n";
        cin >> num1;

        cout << "Enter another number\n";
        cin >> num2;

        cout << "Please enter an operator (+ , * , /, - or End)\n";
        cin >> r;
        if (r == 'End') break;
        if (r == '+') sum = num1 + num2;
        if (r == '-') sum = num1 - num2;
        if (r == '*') sum = num1 * num2;
        if (r == '/') sum = num1 / num2;

        cout << r;
        cout << "The answer is \n" << sum << endl;
        system("pause");
        return 0;
    }
}
xKetjow
  • 17
  • 8

3 Answers3

1

If the user enters 'a' as operator for example (something else than the valid choices), sum is never assigned a value, but sum is printed.

alain
  • 11,939
  • 2
  • 31
  • 51
0

The compiler says that you are trying to use an unintialized variable, sum.

If you think you initialize it, think again: You only assign a value if r is +, -, * or /. But what if r is a? 'End' is not a character, and thus invalid

Then sum is never initialized/has a value, and so the compiler complains.

Rakete1111
  • 47,013
  • 16
  • 123
  • 162
0

As others have said, the variable sum remains uninitialized if the user enters an invalid choice for r. Just set double sum=0; and you're good to go.

In addition, 'End' is not a char, so you can't compare it to r. You'll have to use some other option for ending.

  • True. It should be a char – Bikramjeet Singh Oct 09 '16 at 18:09
  • I did the double sum=0 thing and it got rid of that problem :> What should be a char ? – xKetjow Oct 09 '16 at 18:11
  • Variable r should be a char, not an int. And change 'End' to a single character, say, 'E' – Bikramjeet Singh Oct 09 '16 at 18:16
  • So i changed it, and it works. When I press E it closes so all gud. One more thing, im not sure how to loop it so that the user can enter more than one equation without having to close the program over and over. I have a loop in there, but it doesnt seem to work. – xKetjow Oct 09 '16 at 18:24
  • Your loop doesn't work because you've put return 0 within the body of the loop. Shift it outside to just before the last curly brace } and the loop should work. – Bikramjeet Singh Oct 09 '16 at 18:29