0

The issue I am running into is that when I run the code, it adds correctly but when it comes time to run the if or else statement, nothing happens. It always just ends.

#include <iostream>
using namespace std;

int main()
{
   int firstNumber;
   int secondNumber;
   int sum;
   char restart = 1;

   while (restart == 1)
   {
      cout<<"Welcome to My Calculator!\n\n";
      cout<<"What is the first number you would like to add?\n\n";

      cin>>firstNumber;

      cout<<"What is the second number you would like to add?\n\n";

      cin>>secondNumber;

      cout<<"Wonderful! Getting together your result now....\n\n";
      sum = firstNumber +   secondNumber;
      cout<< sum<<endl;

      cout<<"If you have another question, just enter 1, if not press 2!\n\n";

      cin>>restart;
      if (restart == 1)
      {
         cout<<"No problem!\n\n";

      }
      else
      {

         cout<<"Goodbye!";
      }


   }
   return 0;
}
1
  • Even if you are using int for restart, condition for exit should be restart=0. Numbers other than zeroes are considered true. Commented Jul 17, 2018 at 5:42

1 Answer 1

4
char restart = 1;
if (restart == 1)

needs to be

char restart = '1';
if(restart == '1') 

There is a difference between 1 and '1'. When you want to compare chars you use the '' marks.

Also, you should also always initialize your ints

This is because C++ doesn't automatically set it to zero for you. So, you should initialize it yourself:

int sum = 0;

An uninitialized variable has a random number such as 654654,-5454, etc. (If it doesn't invoke undefined behavior when reading it)

Sign up to request clarification or add additional context in comments.

2 Comments

even the initialization of restart and the test for the while loop need to be fixed.
suggestion, initialize your variables (int's). by doing so you're following the proper path to generating a deterministic program, one that is easier to debug, much more in more advanced cases you're taking simple measures to prevent memory leaks. in doing so, your program performs better and removes ambiguity.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.