stuart194
stuart194

Reputation: 361

How to take a value from stdin when unsure if it's an int or a char?

How would one go about taking a value of stdin when it could be either a character (p or q in this case) or an integer value above zero but below a max?

I have tried using the %c conversion character but find that this means it loses anything after the first digit (obviously as it would just take a single char)

Should I be using %i instead or do I need to do it a different way? I found %i returns 0 for anything not an integer but this would then only allow me to check if it were not an int rather than a specific char?

Cheers

Upvotes: 1

Views: 102

Answers (2)

Andro
Andro

Reputation: 2232

Check it: isaplha for a charachter, and isdigit for a number.

Upvotes: 0

Klas Lindbäck
Klas Lindbäck

Reputation: 33273

Check the return value of scanf:

if (scanf("%d", &intInput) == 0) {
    /* Nothing read. Not an integer! */
    scanf("%c", &charInput);
    /* Process char input */
} else {
    /* Process integer input */

Upvotes: 3

Related Questions