Calculator shut down

I am new to c++. I made a calculator and i "build and run" it and it worked perfectly. then I tried to run the program that was created by the compiler and when I put in the numbers and hit enter the program just shuts down without showing the answer can someone help me?

I use codeblock

#include <iostream>
#include <limits>

using namespace std;

int num1, num2, result;

int main()
{
cout << "Welcome! please enter a number!" << endl;

cin >> num1;

cout << "please enter a number!" << endl;

cin >> num2;

result = num1 * num2;

cout << num1 << " * " << num2 << " is: " <<result << ".\n";


cout << "Press ENTER to continue...";
cin.ignore( numeric_limits<streamsize>::max(), '\n' );

return 0;
}
Last edited on
Your code looks fine.
Replace cout << "Press ENTER to continue..."; cin.ignore(numeric_limits<streamsize>::max(), '\n');
with system("pause");
closed account (1vf9z8AR)
#include<conio.h>
then before return 0; type getch();
maybe its <limit.h>
The problem is when you ask the user for a number, s/he must insert a number and press ‘enter’.
As a consequence, in the input buffer there will be a number plus the character ‘enter’ ('\n').
When you ‘std::cin’ the buffer into an integer variable, there’s no room for the following '\n'.
So it may happen that you need to explicitely tell std::cin to ignore one character after having read numbers.
My personal advice is to avoid system() as long as you can.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <limits>

int main()
{
    std::cout << "Welcome! Please enter a number! ";

    int num1;
    std::cin >> num1;
    std::cin.ignore(1);

    std::cout << "Please enter a number! ";

    int num2;
    std::cin >> num2;
    std::cin.ignore(1);

    int result = num1 * num2;

    std::cout << num1 << " * " << num2 << " is: " << result << ".\n";

    std::cout << "\nPress ENTER to continue...\n";
    std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );

    return 0;
}

Last edited on
Topic archived. No new replies allowed.