Preventing the program from entering an infinite loop when a character is input by mistake


I'd like to write a program that only accepts positive integer inputs.
And if the character q is typed, then the program has to exit.

If anything else is typed (like -3; 0 ; a; b, etc...), then I want it to say, only positive integers are permitted.


Whenever I type a letter, the programs enters an infinite loop.

What should I do to fix this?


Here's part of the code that I have:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include<iostream>
#include<cmath>
#include<cstdlib>
#include <ctype.h>


using namespace std;
int main(void)
{
     //Variables declarations
    int choice;
    char q;

 do {

cout<< "Please enter  a number: " ;
cin>> choice;

if (choice >0){
cout<< "Awesome!"<<endl<<endl;}

else  {
          cout<< "Only positive numbers are accepted."<< endl<<endl ;}






} while (choice != 'q');


    system("PAUSE");
    return 0;
    
 }
Yes, that's because, you are giving an int(integer) type, alphabets, instead of integers.
This sets the badbit flag, and your programme starts to mess-up.

It would be better, if you cin>> in the char(ie: q)
Thanks for the answer, I tried it, unfortunately, for some reason it's not giving me the results that I want.
Here is what I have:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include<iostream>
#include<cmath>
#include<cstdlib>
#include <ctype.h>


using namespace std;
int main(void)
{
     //Variables declarations
    int choice;
    char c;
    char q;

 do {

cout<< "Please enter  a number: " ;
cin>> c;

if (c >0){
cout<< "Awesome!"<<endl<<endl;}

else  {
          cout<< "Only positive numbers are accepted."<< endl<<endl ;}






} while (choice != q);


    system("PAUSE");
    return 0;
    
 }
An identifier, is not the same as a value. while(choice!=q)?? When choice and q do not even have values. This is the correct code, and if you want explanation, maybe tomorrow or from the other guys cause my eyes are heavy.

#include <iostream>

using namespace std;

int main()
{
char input;

do
{
cout«"Enter a number-q to quit: "j
cin»input;
if(input>0)
cout«"\nGood";
else cout«"No negatives allowed";
}while(input!='q');
return 0;
}

Sorry for not using code tags cause I am not on my desktop computer, also, cannot type more......zzzzz............

Good Night!!!
Thanks again,

I try to run this, but whenever I input a negative number (or any letter that is not q by the way), it gives me the same result as if I had put a positive number...

That's why I was hesitating about using char for my cin>>, because I need this to make a distinction between positive numbers, negative numbers, and letters...
Topic archived. No new replies allowed.