Program goes into infinite loop in case of wrong input

mr_azad

I am trying to check the input value, and I run this program below. But when I give a wrong input it goes into infinite loop. I tried the cin.clear(); but still it goes to infinite loop. Please can anyone give me a solution for this.

#include<iostream>
using namespace std;

int main()
{
    int c=0;
    cout<<"in test"<<endl;
    //cin.clear();
    cin>>c;

    if(cin.fail())
        {
            cout<<"please try again"<<endl;
            main();
        }

    else
        cout<<"c = "<<c<<endl;

    return 0;

}
Ayushi Jha

Use cin.ignore() after cin.clear() to remove the invalid input from stream buffer. Using cin.clear() does not remove the previous input, so it keeps going into an infinite loop. cin.clear() only resets the state, i.e., the error flags etc.

Try this:

    cin.ignore(INT_MAX,'\n');

It clears till the first newline is encountered.

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

Circular References in PHPExcel - infinite loop or wrong result

분류에서Dev

React simple fetch program run into an infinite loop

분류에서Dev

getting infinite loop in c while using eof for specific value of input

분류에서Dev

Graphics driver update goes wrong

분류에서Dev

Why does inputting an unexpected value type via scanf() cause this program to enter an infinite loop

분류에서Dev

KnockoutJS and Infinite Loop

분류에서Dev

end infinite loop with command

분류에서Dev

Singleton going into an infinite loop

분류에서Dev

Memory leak in infinite loop

분류에서Dev

Terminating an infinite loop

분류에서Dev

OnClickListener calling wrong case

분류에서Dev

OnResume() causing infinite loop in MainActivity

분류에서Dev

infinite while loop using bufferedreader

분류에서Dev

Robot class, mouseMove in infinite loop

분류에서Dev

Infinite login loop in Debian Virtualbox

분류에서Dev

Recognition of Undecidable Propositions(infinite loop)

분류에서Dev

externally ending infinite loop java

분류에서Dev

What is difference between an infinite loop and an infinite recursive call?

분류에서Dev

Why does this program loop?

분류에서Dev

Stuck in infinite loop after comparing two strings

분류에서Dev

Cannot break out of an infinite loop in c++

분류에서Dev

eof in perl- going in infinite loop

분류에서Dev

setting (custom) delegate runs into infinite loop

분류에서Dev

Express + Angular routing causing infinite loop + crash

분류에서Dev

Why is find exec grep > file an Infinite Loop?

분류에서Dev

How to test an infinite while loop with pytest

분류에서Dev

Laravel App::make causes infinite loop

분류에서Dev

Infinite loop in custom Spring Security application

분류에서Dev

How to set Infinite loop slideshow on tumblr header

Related 관련 기사

뜨겁다태그

보관