HOW TO MAKE A PROGRAM THAT ACCEPTS POSITIVE NUMBER INPUT BUT NOT NEGATIVE NUMBERS OR ALPHABETS?


HOW TO MAKE A PROGRAM THAT ACCEPTS POSITIVE NUMBER INPUT BUT NOT NEGATIVE NUMBERS OR ALPHABET AND INCLUDES LOOP UNTIL WRONG INPUT IS TRUE?
Get input value.
Look at it.
If it's negative or a letter, make user give another input.
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
#include <iostream>

int get_positive_integer()
{
    int number ;
    std::cout << "enter a positive integer: " ;

    if( std::cin >> number ) // if the user entered a number
    {
        if( number > 0 ) return number ; // positive value, return it

        else std::cout << "that is not a positive value. try again.\n" ; // number, but non-positive
    }

    else // the input is non-numeric
    {
        std::cout << "please enter a number. try again.\n" ;
        std::cin.clear() ; // clear the failed state of the input stream
        std::cin.ignore( 1000, '\n' ) ; // remove the bad input from the input buffer
    }

    return get_positive_integer() ; // try again
}

int main()
{
    const int n = get_positive_integer() ;
    std::cout << "\nyou entered " << n << '\n' ;
}
WOW!!! IT WORKS

CAN YOU HELP ME CONVERT IN PSEUDO CODE.
If you have understood the code, you would be able to do that yourself.
If you haven't, ask about the parts that you have difficulty with.

And, please do not shout.
i'm sorry. that's the way I type. i'm still new in this. i honestly don't understand...
What don't you understand? Be specific.
I dont understand psedo code. I dont know how to convert it. I only know it has START and an END.
Also, the usual idea is to write pseudo code first, then turn that into real code.

One can write pseudo code by putting down general ideas of what needs to be done, as comments in the code. Keep going back, put in more detail, until you are happy to convert to real code.

This helps organise ones thoughts.
Topic archived. No new replies allowed.