Search code examples
cinputscanfatoi

C Trying to check for invalid input


I'm using scanf("%s", u); so I take a string. I can take the characters q, c, -, +, /, *, %, ^, =, and integers, but for everything else I want my program to display an error message. How would I know if it's any other character, because if they put anything other than those it will go into an if statement that assumes it's an integer in a string and atoi() it which then equals 0 and spoils things.


Solution

  • You could use a scanf format specifier to ensure that it stops accepting input the moment it encounters one of the invalid characters. %[...]

    It allows you to specify a set of characters to be stored away (likely in an array of chars). Conversion stops when a character that is not in the set is matched. For example, %[0-9] means "match all numbers zero through nine." And %[AD-G34] means "match A, D through G, 3, or 4".

    You can tell scanf() to match characters that are not in the set by putting a caret (^) directly after the %[ and following it with the set, like this: %[^A-C], which means "match all characters that are not A through C."