Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using stringstream to input/output a bool value

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.

like image 737
Andy Avatar asked Nov 24 '13 01:11

Andy


People also ask

How do you read a string in stringstream?

A stringstream associates a string object with a stream allowing you to read from the string as if it were a stream (like cin). str () — to get and set string object whose content is present in stream. operator << — add a string to the stringstream object. stringstream class is extremely useful in parsing input.

What is stringstream in C++?

stringstream in C++ and its applications Difficulty Level : Medium Last Updated : 09 May, 2018 A stringstream associates a string object with a stream allowing you to read from the string as if it were a stream (like cin).

What are the methods of stringstream in Java?

The Stringstream has different methods. These are like below − str (): To get and set the string object whose content is present in stream operator << : This will add one string into the stringstream operator >> : This is used to read from stringstream object.

How to enter true and false values in a line stream?

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 << ' '; }


2 Answers

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.

like image 58
Dietmar Kühl Avatar answered Oct 22 '22 21:10

Dietmar Kühl


Try using the boolalpha manipulator.

lineStream >> boolalpha >> active;
cout << boolalpha << active << endl;

By default, streams input and output bool values as tiny numbers. boolalpha tells the stream to instead use the strings "true" and "false" to represent them.

like image 44
cHao Avatar answered Oct 22 '22 21:10

cHao