cctype and conditional cin usage

Hi! I was doing some programming when I was stuck with a problem.

How do I go about using cctypes? I mean:

1.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <cctype>

using namespace std;

  int main()
{
    cout << "Enter the number of donors: ";
    int no;
    cin >> no;
    cin.get(); // I used this because I did use "cin.get(x,y)" in later parts.
    if (!(isdigit(no)))
    {
        cout << "Enter a number ";
        cin >> no;
        cin.get();
    }
}


Am I doing it wrongly? This doesn't seem to loop, like what I've expected.

Next, if I use !(cin >> no), like in this code:

2.
1
2
3
4
5
6
7
8
9
10
11
int main()
{
    cout << "Enter the number of donors: ";
    int no;
    if (!(cin >> no))
    {
        cin.clear();
        cout << "Enter a number ";
    }
    cin.get();
}

*2. has the same library files as 1.

Why I input something other than a number, it just skips to the end of the code?
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>

int main()
{
    std::cout << "enter the number of donors: " ;

    int number ;
    while( !( std::cin >> number ) || number <= 0 )
    {
        std::cin.clear() ; // clear the failed state
        std::cin.ignore( 1000, '\n' ) ; // throw away the junk input
        std::cout << "please enter a positive number: " ; // ask the user to try again
    }

    std::cout << "number of donors: " << number << '\n' ;
}
There are no loops in either of the programs, so don't expect the program to loop. Perhaps you intended to use "while" instead of "if"

As the name implies, isdigit() checks to see if something is a digit. That something in your case, is quite likely not. Digits are 0 - 9, what you are logically trying to find out is if something is a "NUMBER". 2 is a digit, 4 is a digit, but 24 is not a digit. What answer would you expect from isdigit() in this situation?
Oops, I had forgotten to change the "if" to "while".

I was expecting the function to be able to detect an integer. So in this case, the program couldn't understand and hence it just skips through it?
Topic archived. No new replies allowed.