Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does >> do in c++

Tags:

c++

i'm going through google university section on c++ and i'm not sure what this piece of code does:

if (!(cin >> input_var)) {

    cout << "you entered a non-numeric. Exiting..." << endl;
    break;

}

What does the statement inside the if statement actually do here?

thanks!

like image 871
rage Avatar asked Jan 31 '26 15:01

rage


1 Answers

This is very basic C++. Typically, >> and << are used for bit shifting. However, the I/O stream library has overloaded operator>> and operator<< for streams so that they can be used for extraction and insertion respectively. Why? Because the operator looks like two arrows that have some directionality and so the code reads nicely - data is moving in that direction.

So in your example, cin is the standard input stream and you are extracting an integer from that stream into the variable input_var. You read cin >> input_var as "extract input_var from the standard input".

Similarly, inside the body of your if statement, you are inserting into the standard output stream, cout.

The I/O overloads for operator<< and operator>> return a reference to the stream you're extracting from or inserting into. This stream is convertible to bool to allow you to check its status. That is, doing if (cin) will check if the status of the cin stream is okay. In your case, we are using the "not" operator, !, to check if the stream is not okay. If it's not, we output the error.

It's worth mentioning that the !(cin >> input_var) inside the if statement is not a statement itself - it's an expression.

like image 69
Joseph Mansfield Avatar answered Feb 02 '26 07:02

Joseph Mansfield



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!