Another C++ Q

Status
This thread has been Locked and is not open to further replies. Please start a New Thread if you're having a similar issue. View our Welcome Guide to learn how to use this site.

hyler

Thread Starter
Joined
Jul 30, 2001
Messages
126
When I compile my program, the IF statements fail to work correctly. I ask the user to input my newly defined int variable, and have the IF statements run off of whatever they put in, but no matter what they enter, it starts up on the first IF statement.

int choice;
cin>>choice;
if (choice = 1)
cout<<"Addition-";
cout<<"Enter first number: ";
int first;
cin>>first;
cout<<"Enter second number: ";
int second;
cin>>second;
cout<<first + second;
goto start;
if (choice = 2)
cout<<"Subtraction-";
cout<<"Enter first number: ";
int first1;
cin>>first1;
cout<<"Enter second number: ";
int second1;
cin>>second1;
cout<<first1 - second1;
goto start;
if (choice = 3)
cout<<"Multiplication-";
cout<<"Enter first number: ";
int first2;
cin>>first2;
cout<<"Enter second number: ";
int second2;
cin>>second2;
cout<<first2 * second2;
goto start;
if (choice = 4)
cout<<"Division-";
cout<<"Enter first number: ";
int first3;
cin>>first3;
cout<<"Enter second number: ";
int second3;
cin>>second3;
cout<<first3 / second3;
goto start;
}
 
Joined
Nov 2, 2000
Messages
637
to check you need two = signs, not just one. All you are doing is setting choice = 1 each time.
 

Guy

Joined
Feb 19, 1999
Messages
260
Just thought I would add that a good coding habit to get into that will help new coders (and advanced one too :p) locate this common error easily is to put the constant as the first element in the check. If you do this the error will be produced at compile time and is much easier to remedy.

ie:
Code:
// do it like this
if(1 == choice)
{
...
}
// rather than like this
if(choice == 1)
{
...
}
if you leave out an = sign in the first if statement, you will get a compile time error because you cannot assing a value to a constant, but if you do it the second way, the program will run, but it will behave strangely and unexpectedly.

Cheers
 
Status
This thread has been Locked and is not open to further replies. Please start a New Thread if you're having a similar issue. View our Welcome Guide to learn how to use this site.

Users Who Are Viewing This Thread (Users: 0, Guests: 1)

As Seen On
As Seen On...

Welcome to Tech Support Guy!

Are you looking for the solution to your computer problem? Join our site today to ask your question. This site is completely free -- paid for by advertisers and donations.

If you're not already familiar with forums, watch our Welcome Guide to get started.

Join over 807,865 other people just like you!

Latest posts

Members online

Top