what this is supposed to do is act as a simple addition calculator, and is completely normal, until someone enters 2 + 2, then it would say it equals 5, but then go back to being a normal addition calculator, unless of course they add 2 and 2 again.
Exactly what satchmo05 says. You are assigning values to 'a' and 'b', which will ALWAYS result in true (unless your are replacing it with 0). Change the code to what satchmo05 suggested.
It has something to do with a '\n' being left in the input buffer after you use cin>>
If you change your code to:
1 2 3 4 5 6 7
int a,b,c;
cout <<"Enter a number: ";
cin >> a;
cin.ignore(); // <-- new code here
cout <<"Enter a number: ";
cin >> b;
cin.ignore(); // <-- new code here
It isn't directly necessary for cin.get(). For example:
1 2 3 4 5 6 7 8 9 10
#include <iostream>
using namesapce std;
int main()
{
cout << "Hello um0123!";
cin.get();
return 0;
}
This program uses cin.get() and will pause the program until its gets a character(most often enter). However, it doesn't use cin.ignore() does it.
As i said, its has soemthing to do with a newline, or '\n', being left in the input buffer when you use cin >> a. cin.ignore() takes up to 3 arguments but by default, will just ignore '\n' when it finds it. That's why you have to use it when you ask for both numbers.
Unfortunately I can't tell you why it does this but I would be interested to know why the program does close if you don't use it, if anyone can explain?
#include <iostream>
using namesapce std;
int main()
{
int a = 0;
cout << "Hello world!" << endl << "Enter a number: ";
cin >> a; //here there is a \n left in the buffer
cout << "You input: "<<a<<endl;
cin.get(); //without a cin.ignore(), cin.get() will see the \n and "get" it
//then the program will end
return 0;
}
#include <iostream>
usingnamespace std;
int main()
{
int a = 0, b = 0;
cout << "Hello world!" << endl << "Enter a number: ";
cin >> a; //here there is a \n left in the buffer
cout << "You input: "<<a<<endl;
cout << "\n Enter another number: ";
cin >> b;
cout << "You input " <<b<<endl;
cin.get(); //without a cin.ignore(), cin.get() will see the \n and "get" it
//then the program will end
return 0;
}
The program doesn't ignore the '\n' so does it get carried into the b variable? :S
No. This is because cin >> will read everything until the \n and put it into the variable, so in this case, you are putting nothing into the variable (which means it will probably become some garbage value). IIRC how it works anyway.