Reputation: 41
I'm fairly new to the programming world and I had a school assignment to create a simple program containing an if loop. Basically, I want my code to return true if a is greater than 18, and false if a is less than 18. I also want a to increase by one each time canTakeRoadtest returns false. When I run my code all I get is
"I am 0 years old.
I can take my road test. 0"
I'm wondering why bool canTakeRoadtest is returning an integer, and why a isn't incrementing. Any help would be appreciated and I apologize for the simple question but we all start somewhere!
My coding environment is Eclipse Neon if it makes any difference.
#include <iostream>
using namespace std;
int main() {
//Local Variables
int a = 0;
bool canTakeRoadtest = false;
//If Loop
if (a >= 18) {
canTakeRoadtest = true;
cout << "I'm ready!\n";
} else {
canTakeRoadtest = false;
cout << "I am " << a << " years old.\n";
cout << "I can take my road test. " << canTakeRoadtest << endl;
a++;
}
//return 0;
}
Upvotes: 4
Views: 3355
Reputation:
Behind the scenes, every variable type in C++ has a number representation. This makes sense because at the base level of a computer, all there is is numbers. There are two main primitive data types that are (usually) represented as something other than a number, but are really just numbers. The first one is bool, and the second one is char.
For example, if you set
bool myBool = true;
behind the scenes, it is really setting your variable to 1. Similarly, if you set
myBool = false;
it will be 0 behind the scenes. The same rule applies for chars. If you set
char myChar = 'a';
it really is setting the char to 97. Every character has a number representation, and you can see these if you look at this table.
So, as to why cout is displaying the number representation of a bool rather than in "English", this is simply because whoever coded iostream decided that when you give it a bool it displays the number representation instead of the "English" representation. The same does not apply for chars, however. They will be represented as a character by iostream.
To fix iostream from printing out the incorrect representation, change your code from
cout << "I can take my road test. " << canTakeRoadtest << endl;
to
cout << "I can take my road test. false" << endl;
You could also use boolalpha, as Lovelace42 stated.
Upvotes: 4
Reputation: 64
Use boolalpha. By default bool values are integers, boolaplpha sets the bool flag to output its textual representation
http://www.cplusplus.com/reference/ios/boolalpha/
Or you can just change your cout statement.
if (a >= 18) {
canTakeRoadtest = true;
cout << "I'm ready!\n";
} else {
canTakeRoadtest = false;
cout << "I am " << a << " years old.\n";
cout << "I can take my road test. false" << endl;
a++;
}
Upvotes: 2