简体   繁体   中英

Why I can't do arithmetic operations in console input “cin”?

I am a beginner to C++. I am having some trouble or doubt; The thing is, I am giving an arithmetic operation such as 2+2 in user input cin>> . But in return it gives output of 2!

Code:

#include "iostream"
using namespace std;
int main(){
    int t;
    cin>>t;      // Here I Have Given 2+2
    cout<<t;     // Instead of giving 4; It is giving me 2
    return 0;
}

Is There any solution to this? Please Help Me!

You declare t as an integer. You give "2+2" in input. That is no int, that's a string and cin reads the first integer from the input.

cin>>t;
cout<<t+t;

This would print 4. But the point here is that you can't assign arithmetic operations to cin. You need to create them in the code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM