Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

My cin.get() is not working and hence does not stop the code

I’m a beginner and learing C++. When I try to run the exe file of this code it closes as soon as I press ‘enter’ after entering the second number. How do I pause my code to see the result?
I also tried system("pause"), it worked but I read that it only works on windows and using it is considered BAD PRACTICE, so I want to do it in a proper way. Please help

Print.h (header file I used in the main code)

#pragma once
#include <iostream>
template<typename T> void print(T arg, int newline=1)
{
    if (newline)
        std::cout << arg << std::endl;
    else
        std::cout << arg;
}
#include <iostream>
#include <string>
#include "../Print.h"


void calculator()
{
    print("Enter the first number: ", 0);
    int num1;
    std::cin >> num1;
    print("Choose Operation (+ - x /): ", 0);
    std::string  operation = "";
    std::cin >> operation;
    print("Enter the second number: ", 0);
    int num2;
    std::cin >> num2;
    if (operation == "+") {
        print("Output ==> ", 0);
        print(num1 + num2);
    }
    else if (operation == "-") {
        print("Output ==> ", 0);
        print(num1 - num2);
    }
    else if (operation == "x") {
        print("Output ==> ", 0);
        print(num1 * num2);
    }
    else if (operation == "/") {
        print("Output ==> ", 0);
        print(num1 / num2);
    }
    else {
        print("Error: Invalid Operation!\nPlease try again.");
        calculator();
    }

}

int main()
{
    print("Welcome!\nLets start!!");
    calculator();
    std::cin.get();
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Here’s a possible way to do what you are asking for

std::cin.ignore(INT_MAX, '\n'); // ignore any pending input
std::cin.get();                 // now wait for some new input

What beginners forget is that input can be left behind after you have read something. That left behind input is still there the next time that you read something, it doesn’t go away.

You can read about the ignore method here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading