-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,?

student
  • 1
  • 3
  • Looks correct to me. What output do you think you should get? – john Sep 01 '18 at 06:58
  • How does cin work here – student Sep 01 '18 at 07:05
  • 4
    After your input a is 123 and b is a comma. Then you output the same. I really don't understand why you think it should be any different. What did you expect to happen? – john Sep 01 '18 at 07:08
  • @john, why does `char b[] = {}`; instead of `char b;` affects `cout< – iGian Sep 01 '18 at 11:56
  • @iGian Your version has undefined behaviour because you are reading input into an empty array. – john Sep 02 '18 at 07:56
  • @john, thanks. Still stuck. Actually, if I use `int a;` and `char b[] = "b";` then input just one char to `cin >> b;`, the `cout<>b`, the `cout<>a;` is not. I'd expect `cout< – iGian Sep 02 '18 at 09:12
  • 1
    @iGian You might be right about a backwards override but the only C++ answer is that it's undefined behaviour. Incidentally you need one more character in the array than characters input because `cin>>b` adds a terminating nul character to the array as well as the input characters. – john Sep 02 '18 at 09:18
  • 1
    @iGian For resources try googling 'buffer overflow' – john Sep 02 '18 at 09:21

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;