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.
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.
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).
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.
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 << ' '; }
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With