Difference between scanf() and strtol() / strtod() in parsing numbers

后端 未结 8 1596
陌清茗
陌清茗 2020-12-05 20:28

Note: I completely reworked the question to more properly reflect what I am setting the bounty for. Please excuse any inconsistencies with already-given ans

相关标签:
8条回答
  • 2020-12-05 21:02

    To summarize what should happen according to the standard when parsing numbers:

    • if fscanf() succeeds, the result must be identical to the one obtained via strto*()
    • in contrast to strto*(), fscanf() fails if

      the longest sequence of input characters [...] which is, or is a prefix of, a matching input sequence

      according to the definition of fscanf() is not

      the longest initial subsequence [...] that is of the expected form

      according to the definition of strto*()

    This is somewhat ugly, but a necessary consequence of the requirement that fscanf() should be greedy, but can't push back more than one character.

    Some library implementators opted for differing behaviour. In my opinion

    • letting strto*() fail to make results consistent is stupid (bad mingw)
    • pushing back more than one character so fscanf() accepts all values accepted by strto*() violates the standard, but is justified (hurray for newlib if they didn't botch strto*() :()
    • not pushing back the non-matching characters but still only parsing the ones of 'expected form' seems dubious as characters vanish into thin air (bad glibc)
    0 讨论(0)
  • 2020-12-05 21:08

    I don't believe the parsing is allowed to produce different results. The Plaugher reference is just pointing out that the strtol() implementation might be a different, more efficient version as it has complete access to the entire string.

    0 讨论(0)
提交回复
热议问题