cin.ignore, get, cin?

Hey I have this:

1
2
3
4
5
6
 do {
        cout<<"How many: ";
        cin.get();
        cin>>num;
        cin.ignore();
        }while ((num<1)||(num>3));

The problem is if I input something "djkhgf", it stucks in a infinity loop. Can someone tell me what is the problem or how can i control the user's input between 1-3 ?
Invalid input puts it in a state of error and input stuff instantly returns. Throw a cin.clear(); before any input.
still same... infinity loop :\

1
2
3
4
5
6
 do {
        cout<<"How many: ";
        cin.clear();
        cin>>num;
        cin.ignore();
        }while ((num<1)||(num>3));


note: num is an integer...
Last edited on
It's going into an infinite loop because an iostream turns into a zombie object on error. Use cin.clear() every iteration, or use the better-designed, faster stdio.h library.
there is already a cin.clear() line in the loop. but still infinite loop occurs if i input "ldkfg" etc... any other ideas? or what is this "faster stdio.h lib" ? any example pls?
Try this way:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <fstream>
#include <limits>
using namespace std;
int main()
{
    int num;
    do {
        cout << "How many: ";
        cin >> num;
        if(!cin)
        {
            cout << "This wasn't even a number!\n";
            cin.clear();
            cin.ignore(numeric_limits<streamsize>::max(), '\n');
        }
    } while (num<1 || num>3);
    cout << "You've entered " << num << '\n';
}


demo: http://ideone.com/LTPtS
Last edited on
thank you @cubbi, it works perfect.
whocares21, the reason your code still goes into infinite loop is that if cin>>num; fails the it goes into error state so cin.ignore(); will do nothing. cin.clear(); clears the error state.cin>>num; reads the same input again and of course fails again. And there you have an infinite loop.

Example of using the stdio.h library:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <string>
#include "stdio.h"
using namespace std;
int main(){
    int num;
    do {
        puts("How many: ");
        char s[100];
	fgets(s,100,stdin);
	if(!sscanf(s,"%d",&num))
            puts("This wasn't even a number!\n");
    } while (num<1 || num>3);
    printf("You've entered %d\n",num);
}

Note, you should read up on it here:
http://www.cplusplus.com/reference/clibrary/cstdio/
Last edited on
Do not use stdio.h, it is deprecated. <cstdio> is the same but in the std namespace, so no using that either.

As for why it still infinite loops with cin.clear(), put a cin.sync() right after the cin.clear(). Peter explained why.
Last edited on
Topic archived. No new replies allowed.