Am new to programming and was facing a problem.
This is not the code I was having trouble with but this explains my issue.
It prints both x and y no matter what I input in a. At the end the result of the cout command tells that "a" is 2 no matter what I input at the start of the program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream>
usingnamespace std;
void main()
{
int a;
cin >> a;
if (a = 1)
{
cout << "x"<<endl;
}
if (a = 2)
{
cout << "y"<<endl;
}
cout << a;
system("pause");
}
You need to use two equals signs (==) to compare for equality.
One equal sign is the assignment operator.
Basically, your code is doing this:
1 2 3 4 5 6 7 8 9
int a;
cin >> a;
a = 1; // Set a equal to 1
if (a != 0)
cout << "x" << endl;
a = 2; // Set a equal to 2
if (a != 0)
cout << "y" << endl;
cout << a; // Prints 2
Also, main should be declared as int main(), not void main().
And technically, you need to #include <cstdlib> to use system().