Need Help with Basic Calculator

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";

cin.get();
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#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";

	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?
Sticky thread on top of the list: http://www.cplusplus.com/forum/beginner/1988/

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.
Last edited on
Thanks.
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!
Topic archived. No new replies allowed.