Can we write a scanf function to parse input on # sign and read two numbers?
since # is not used in aa standard way i am a bit confused
CodePudding user response:
The scanf pattern "%d#%d" matches, in order:
- optional whitespace
- an integer
- the character
# - more optional whitespace
- another integer It returns 2 if both integers were found.
If there is anything (even a space character) between the first integer and the #, the scan will stop after the first integer and return 1. It will also stop and return 1 if whatever follows the # is not an integer possibly preceded by whitespace. This imprecision is one of the reasons scanf is often discouraged.
You could allow whitespace before the # by adding a space into the pattern: "%d #%d". But whitespace includes newline characters, which can lead to unexpected behaviour. That's another reason scanf is often discouraged.
In summary:
- Yes, you can get scanf to read a line consisting of two numbers separated by a
#. Not a problem; scanf does not have a concept of "legal delimiter". - If the input is from an error-prone source, such as a human typist, scanf makes it difficult to produce good error messages, which can be a frustrating experience. But if you know the input is error-free, scanf will work just fine.
In the above patterns, if you want to accept floating point numbers, change the %d to %lf (for doubles, generally recommended) or %f fir floats.
