I’m a beginner to C++ and I’m having a problem with this code, which is supposed to display the scores during the Superbowl final:
#include <iostream>
enum POINTS { EXTRA_POINT = 1, SAFETY = 2, FIELD_GOAL = 3, TOUCHDOWN =6 };
unsigned short giantsScore = 0, patriotsScore = 0;
int main()
{
std::cout << " Giants: " << giantsScore << "\n";
std::cout << " Patriots: " << patriotsScore << "\n\n";
std::cout << " Giants: " << giantsScore = giantsScore + SAFETY << "\n";
std::cout << " Patriots: " << patriotsScore << "\n\n";
std::cout << " Giants: " << giantsScore = giantsScore + TOUCHDOWN + EXTRA_POINT << "\n";
std::cout << " Patriots: " << patriotsScore << "\n\n";
std::cout << " Giants: " << giantsScore << "\n";
std::cout << " Patriots: " << patriotsScore = patriotsScore + FIELD_GOAL << "\n\n";
std::cout << " Giants: " << giantsScore << "\n";
std::cout << " Patriots: " << patriotsScore = patriotsScore + TOUCHDOWN + EXTRA_POINT << "\n\n";
std::cout << " Giants: " << giantsScore << "\n";
std::cout << " Patriots: " << patriotsScore = patriotsScore + TOUCHDOWN + EXTRA_POINT << "\n\n";
std::cout << " Giants: " << giantsScore = giantsScore + FIELD_GOAL << "\n";
std::cout << " Patriots: " << patriotsScore << "\n\n";
std::cout << " Giants: " << giantsScore = giantsScore + FIELD_GOAL << "\n";
std::cout << " Patriots: " << patriotsScore << "\n\n";
std::cout << " Giants: " << giantsScore << "\n";
std::cout << " Patriots: " << patriotsScore = patriotsScore + FIELD_GOAL + EXTRA_POINT << "\n\n";
return 0;
}
Ignoring that this is quite inelegant, when I run this through the compiler, G++, I get the error message
error: invalid operands of types ‘int’ and ‘const char [2]’ to binary ‘operator<<‘
If I remove the constants and add them in before each std::cout, then it runs fine. I just wanted to know why I can’t add the constants during each output line?
Your error message states:
int << char, which of course is an odd operation.It is because of operator priorities.
Each operator has a priority meaning it will evaluate before or after the other operators are evaluated.
+evaluates before=and
<<should be evaluated after=hadcout<<"stuff"been its original purpose.<<is originally the bit-shift operator (still is), so that is why you are experiencing this odd behaviour. Add parentheses and you’ll be good.