-5

I'm new to C++, and I want learn how the following code generates output?

int main(){
    int a;
    char b;
    cin>>a; 
    cin>>b;
    cout<<a<<b;
}

I input 123 for a and , for b. But how come the line cout<<a<<b give output of 123,?

2 Answers2

1

In cin>>a>>b when you enter 123, a is an integer, c++ starts to find an integer. It detects 123 but , isn't an integer so cin fails to detect this. When a cin fails it goes to the next command and the next command is to read a character b and it reads ,. I hope this was helpful!

-1

This happening because you have two different data types declared as "a" is type "int" while "b" is type "char" and moreover C++ takes '123' as single int-input. Hope this helps. Quick Fix: Avoid Char Input after int as when you press return (enter-key) char is inputted to it's ascii-value. Code Snippet:

int a;
char b;
cin>>a;
cout<<a<<endl;
cin>>b;
cout<<b<<endl;
Ali Asadullah Shah
  • 85
  • 1
  • 1
  • 12