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
258 views
in Technique[技术] by (71.8m points)

c++ - How cin>>x returns bool type value in if(cin>>x) but not while cout<<(cin>>x);

Code

#include<iostream>
int main()
{
    int x;
    std::cout<<(std::cin>>x)<<"
";
    
    std::cin.clear();
    std::cin.ignore();
    
    if(std::cin>>x)
    {
        std::cout<<"inside the if-block
";
    }
}

Output-1

2                  // input-1
0x486650
3                 // input-2
inside the if-block

for input 2 cin>>x succeeds but gives 0x486650

for input 3 if-block executed means it returns 1.

Output-2

a                 // input-1
0
b                 // input-2

for input a cin>>x fails and gives 0 as expected.

for input b cin>>x if-block not executed means it returns 0

So why std::cout<<(std::cin>>x) returns something like 0x486650 when succeeds ?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Before C++11 streams didn't have an operator bool() and had an operator void*() instead, see https://en.cppreference.com/w/cpp/io/basic_ios/operator_bool.

When used as intended i.e.:

if (std::cin)
{
}

or:

if (std::cin >> x)
{
}

There is no difference between the C++11 and pre C++11 behaviour.

However if you try to directly print a stream:

std::cout<<std::cin;

In C++11 this fails to compile as there is no standard stream operator that takes an input stream and the boolean conversion operator is marked as explicit.

In C++03 however the void* conversion is not explicit so "printing" an input stream results in the fairly surprising behaviour of printing a pointer. If the stream is in a failed state the pointer will be null so 0 will be printed. If the stream isn't in a failed state the pointer will be non-null (possibly a pointer to the stream itself, this isn't specified by the standard) so will result in a non-zero address being printed. e.g. see https://godbolt.org/z/dM3ce5Kes


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

...