Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
313 views
in Technique[技术] by (71.8m points)

c++ - cin and boolean input

I am new to C++ and I was wondering how the function cin in case of a boolean data works. Let's say for instance :

bool a;
cin >> a;

I understand that if I give 0 or 1, my data a will be either true or false. But what happens if I give another integer or even a string ?

I was working on the following code :

#include <iostream>

using namespace std;

int main()
{
    bool aSmile, bSmile;
    cout << "a smiling ?" << endl;
    cin >> aSmile;
    cout << "b smiling ?" << endl;
    cin >> bSmile;
    if (aSmile && bSmile == true)
        cout << "problem";
    else
        cout << "no problem";
    return 0;
}

If I give the values of 0 or 1 for both boolean, there is no problem. But if I give another integer, here is the output :

a smiling ?
9
b smiling ?
problem

I am not asked to enter any value to bSmile, the line cin >> bSmile seems to be skipped. The same happens if I give a string value to aSmile.

What happened?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

From cppreference:

If the type of v is bool and boolalpha is not set, then if the value to be stored is ?0?, false is stored, if the value to be stored is 1, true is stored, for any other value std::ios_base::failbit is assigned to err and true is stored.

Since you entered a value that was not 0 or 1 (or even "true" or "false") the stream set an error bit in its stream state, preventing you from performing any further input.

clear() should be called before reading into bSmile. Also, this is a good reason why you should always check if your input suceeded with a conditional on the stream itself.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...