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;
}
#include <iostream>
usingnamespace 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;
}
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.