Weird Error

I'm writing a c++ program in visual studio that reads lines from a file and performs the bitwise operator indicated by the file line. For some reason when I read in the file the program gives me wrong answers when using the & operator but not the >> operator. Also the final line in the file gets read twice, can anyone point out the problem?

Code:


#include <iostream>
#include <string>
#include <fstream>
#include <iomanip>

using namespace std;

void PrintBinary(int number)
{
unsigned int MASK = 0x80000000;
cout << number << " = ";
for (int i = 0; i < 32; i++)
{
if((number & MASK) !=0)
{
cout << "1";
}
else
{
cout << "0";
}
MASK = (MASK >> 1);
}
cout << endl;
}

void PrintOut(string bitwise_operator, int binNum1, int binNum2, int binNum3)
{
cout << "Applying the bitwise operator " << bitwise_operator
<< " to the following"<< "\n";
PrintBinary(binNum1);
PrintBinary(binNum2);

cout << "\n" << "Produces: ";
PrintBinary(binNum3);
cout << endl;
}


int main()
{
int answer, a, b;
string expression, line;

ifstream f("Input.txt");
if (!f)
{
cout << "Error: Could not find file! " << endl;
}
while(!f.eof())
{
f >> expression >> a >> b;
cout << expression << " " << a << " " << b << endl;
if(expression == ("&") || ("&="))
{
answer = a & b;
}

else if(expression == ("|") || ("|="))
{
answer = a | b;
}

else if(expression == ("^") || ("!="))
{
answer = a ^ b;
}

else if(expression == ("~"))
{
answer = ~ a;
}

else if(expression == ("<<") || ("<<="))
{
answer = a << b;
}

else if(expression == (">>") || (">>="))
{
answer = a >> b;
}
cout << answer << endl;
PrintOut(expression, a, b, answer);
}

system("pause");
return 0;
}

File: Input.txt:
& 13 27
>> 960 8

Your If statements are wrong, none of the should work. For example:
Your code is and will never evaluate properly:
1
2
if(expression == ("&") || ("&="))
{


it should be:
1
2
if( (expression == "&") || (expression == "&=") )
{


If you tried others in that ladder if system you have you would only find they all don't work because of that simple error. The way you had it it doesn't test expression against both strings, it assumes that one of those will always be true.

I don't see any problems with the math except the fact that the ifs are preventing something from happpening.
[Facepalm]
Thanks that fixed it!
Topic archived. No new replies allowed.