Hi, Im new to programming C++, just started to self learn it recently.
I was trying to create a basic calculator but when I add cin.get() in the end, it closes right after I input the numbers and shows the results for like a split second. This happens with all the programs that use cin as input. Why can't they stay like they normally do when I use, cin.get(), return 0. Can someone find a solution to this or explain it.
#include <iostream>
using namespace std;
int num1, num2, result;
int main()
{
cout << "Please enter the first number: ";
cin >> num1;
cout << "Please enter the second number: ";
cin >> num2;
result = num1 + num2;
cout << num1 << " plus " << num2 << " is " << " is equal to: " << result << ".\n";
#include <iostream>
usingnamespace std;
int num1, num2, result;
int main()
{
cout << "Please enter the first number: ";
cin >> num1;
cout << "Please enter the second number: ";
cin >> num2;
result = num1 + num2;
cout << num1 << " plus " << num2 << " is " << " is equal to: " << result << ".\n";
cin.get();
return 0;
}
You just posted the exact same code that I had. Why does this code work if I use it on the site but when I use it on c++ on my computer, it disappears in a split second after giving the result?
What happens is that until cin runs out of characters to read from the input stream, it won't pause.
When you do cin >> variable; cin will try to read input until it encounters a character that it's not a number (waiting for more input if it can't find any). When it finds that character, it stops reading, leaves the character as the next to be read, and returns the number.
Since you hit enter to confirm the input, you actually insert a newline character after the number. When cin.get() tries to read a character it finds that newline and continues immediately.
This happens also after the first cin extraction, but the second extraction ignores any input left in the input buffer until it finds a character that can be interpreted as a number (or pause and wait for more).
I'm guessing your terminal flashes because you're on windows and executing the program by double-clicking. If you execute it directly from a terminal it should stay open.
If you are using visual studio 2013... you want to "start without debugging." Ctrl + F5. you can find this under the debug tab. press any key to continue.... cheers!