-1

I decided to write the code in such a manner where both inputs are from the user and the system adds the value to give the sum of the 2 values provided by the user. but the out is different from what I expected it to do. please refer to the respective attached block of the result

*I really hope that someone could help me understand what exactly is going on with the block of code I have written, Please also help me with typing the code more efficiently -`

Please refer to my code and attachments

Here is my actual code

`

#include <iostream>
#include <string>

using namespace std;

int main()
{
    int nm1, nm2;
    cout<<"Your numbers please";

    cin >> nm1, nm2 ;  
    cout << nm1 + nm2;

    return 0 ;


}

`

I was expecting a sum and it gave me some sort of a big surprise

PS E:\programmes\C programming> cd "e:\programmes\C programming" ; if ($?Your numbers please1 2 4201052 PS E:\programmes\C programming> cd "e:\programmes\C programming" ; if ($?) { g++ c++intros2.cpp -o c++intros2 } ; if ($?) { .\c++intros2 } Your numbers please1 4201052

I also hope that someone could give me some intel and also provide me with a good and more efficient code instead of referring me to this one -

`

#include <iostream>
#include <string>

using namespace std;

int main()
{
    int nm1, nm2;
    cout<<"Your numbers please";

    cout << "Your 1st number please";
    cin >> nm1 ;
    cout << "Your 2nd number please"; 
    cin >> nm2 ;
    cout << nm1 + nm2;

    return 0 ;


}

`

Thanking you

Sidou Gmr
  • 138
  • 8
  • `cin >> nm1, nm2 ; ` should be `cin >> nm1 >>nm2 ; ` Learn about the comma operator if you are going to use it: [https://stackoverflow.com/questions/54142/how-does-the-comma-operator-work](https://stackoverflow.com/questions/54142/how-does-the-comma-operator-work) it will do very unexpected things if you try to guess what it does. – drescherjm Nov 13 '22 at 13:24

1 Answers1

0

If you take a good look of both your codes, you can see where the main problem is;
The difference (beside cout comments) are into these lines: cin >> nm1, nm2; and cin >> nm1; cin >> nm2;

And the reason you got a big surprise is that you misread(incorrect syntax) multiple integers from the input stream; You can use commas like that int nm1, nm2, nm3, nm4; and declare multiple integers, but you need different syntax while reading or writing - which would be: cin >> nm1 >> nm2; and does same as cin >> nm1; cin >> nm2;

Same goes for cout for better understanding - cout << "Your Sum is "; cout << nm1+nm2; and cout << "Your sum is " << nm1+nm2; will do the same.

And probably you should try the suggested links in the comments too, like:

How Comma Operator works

What exactly are cout/cin

What is the << operator for in C++