質問

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.

役に立ちましたか?

解決

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."

他のヒント

The short answer is that scanf() is the wrong tool for this job. You should probably consider fgets() (or an equivalent such as readline() from POSIX 2008). This will read a whole line into memory. You can then parse the string, possibly using sscanf(), possibly some other 'tokenizing' mechanism that recognizes valid tokens (sequences of one or more characters) and errors.

See the code at Why does this accept invalid input? for an example of how to read one number per input line. You'd want to adapt that to your purposes; it is not quite appropriate as it stands, but it is a good starting point for the number parsing. Note too that atoi() does no error detection; it is only suitable for very benign environment (such as the one you're probably working in).

One alternative is to just always scan a string and loop trough it and check for the conditions you want and if it don't pass you send the error message, else you use it. I believe that would be the most trivial way since the input is always chars.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top