Hi, I wrote this code but why writing 0 it print true instead of false?
Thanks!
#include <iostream>
int main ()
{
bool a;
std::cout << "insert 0 or 1:";
std::cin >> a;
if (a=true)
{
std::cout << "a is true";
}
else
{
std::cout << "a is false";
}
}
Printable View
Hi, I wrote this code but why writing 0 it print true instead of false?
Thanks!
#include <iostream>
int main ()
{
bool a;
std::cout << "insert 0 or 1:";
std::cin >> a;
if (a=true)
{
std::cout << "a is true";
}
else
{
std::cout << "a is false";
}
}
Code:if (a=true) // should be ==
welcome to c++ gotchas 101 :D
thanks now it works :D
if a number bigger then 1 is true, why writing for example 8 it print false?
but it print false...
See this FAQ. Int a nutshell, don't try to assign int values to a bool. Acceptable values are true and false.
http://www.codeguru.com/forum/showthread.php?t=332831
Excuse me I don't see the code button, however my updated code is this and typing a number bigger then 1 it print false:
Code:#include <iostream>
int main ()
{
bool a;
std::cout << "insert 0 or 1:";
std::cin >> a;
if (a==true)
{
std::cout << "a is true";
}
else
{
std::cout << "a is false";
}
}
An bool in c++ is 1 byte (8 bits) if you store the value 7 in that byte and compare it with the value 1 (true) it will go on the false branch (because those values are not equal) even if they both evaluate to true.
You can modify the code like this and then you will get the desired behavior:
Code://...
if(a)
//...
in input a bool must be only 0 or 1 ?
how can i write a text like "Hello \n" but considering \n a normal text?
No, that is what i tried to explain to you, a bool can store other values, since it is not a single bit (it's 8)
You need to double the \ to appear:
Code:cout << "Hello \\n";
@GCDEF agree with you that it shouldn't, but it can and there can be some very tricky situations regarding this fact.
I talk about for example uninitialized bool which can return false if compared to true and again false if compared to false, so the programmer should know that the bool can store 8 bits not just 1.
//my bad that i didn't specifically said that it's not recommended to use bool for storing anything else than true or false.
What is the purpose of having a bool as input if you want to store more values? Why not just make it an int instead of a bool?
Now there is no issue. Since you want 0 to mean false, and anything else to mean true, then this is guaranteed to work correctly.Code:#include <iostream>
int main ()
{
bool a;
int value;
std::cout << "insert 0 or 1:";
std::cin >> value;
a = (value?true:false);
}
Regards,
Paul McKenzie