Using stringstream to input/output a bool value

Andy picture Andy · Nov 24, 2013 · Viewed 9.6k times · Source

this may seem like a stupid question but i am stumped. Here is my code:

int main()
{
    string line, command;
    getline(cin, line);
    stringstream lineStream(line);

    bool active;
    lineStream >>active;
    cout <<active<<endl;

}

no matter what i input for active, it always prints out 0. so lets say my input was

true

it would output 0 and same thing for false.

Answer

Dietmar K&#252;hl picture Dietmar Kühl · Nov 24, 2013

You should always verify if your input was successful: you'll find it was not. You want to try the value 1 with your current setup:

if (lineStream >> active) {
    std::cout << active << '\n';
}
else {
    std::cout << "failed to read a Boolean value.\n";
}

If you want to be able to enter true and false, you'll need to use std::boolalpha:

if (lineStream >> std::boolalpha >> active) {
    std::cout << std::boolalpha << active << '\n';
}

The formatting flag changes the way bool is formatted to use locale-dependent strings.