2

I have written the following function:

void check(int* input){

do{
    std::cout<<"Enter integer!";
    std::cin>>*input;
}while(!std::cin);
}

And I am using it in the main function as follows:

int main()
{
    int *k;
    k=new int;
    check(k);
    std::cout<<"Value of the k is:"<<*k<<"in address"<<k;
    return 0;
}

The problem is when user input some characters, the compiler keep printing "Enter integer!", non-stop, and I have to stop the compiler manually.

2
  • 2
    Unrelated to your problem, but why do you allocate the integer dynamically in main? Why use pointers at all? Why not simple references? Commented Mar 23, 2018 at 7:08
  • 3
    As for your problem, it's well-known problem with plenty of duplicates here. It stems from the input not being removed from the buffer. You need to clear or ignore the existing input. Commented Mar 23, 2018 at 7:10

1 Answer 1

1

What is happening is the stream is breaking. Basically, the program sees a character going into something that isn't a character and freaks out, which is UB. It is a simple fix you can find in just about any beginning level books that include data validation:

#include <limits>

if(cin.fail())
{
    cin.clear();
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
}

This tests if the stream is broken, clear the flag and ignore the rest of the input on the line.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.