Infinite Loop of death

So im stuck in a loop and a hard place i have this code and when i accidentally input a letter instead of a number then the infinite loop of death wil scatter like ants covering a melted ice cream!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <conio>

int main (){
main:
clrscr();
cout<<"Enter whatever: ";
int a; cin>>a;

switch(a){
case 1: cout<<"congrats you didnt input a letter!";
default: goto main;
//when i input a letter it will trigger the //loop of death

}
getch();
return 0;
} 
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>

using namespace std;

int main ()
{
    cout << "Enter whatever: ";
    int a;

    while (!(cin>>a))
    {
        cout << "sorry, that isn't an integer. Please try again." << endl;
        cin.clear();            // reset the error flags
        cin.ignore(1000, '\n'); // empty the input buffer
    }
    
    cout << "The number was: " << a << endl;
} 
Thanks Ill try it later didnt know those exist Im still learning and have just been serious when coding in c++ a few weeks back..
If you want a loop, then write a loop. Do not use goto.

The conio, clrscr(), and getch() are non-standard and deprecated. There are modern alternatives.


When the input operation sees an error (e.g non-numeric characters, when integer is expected) the stream has its state set to error. When stream is in state error, all further input operations will fail immediately.

You have check the state after each read and if it is error, then clear the error and discard the contents of the stream before next read.
Topic archived. No new replies allowed.