How do I tell if the c function atoi failed or if it was a string of zeros?

后端 未结 6 1460
悲&欢浪女
悲&欢浪女 2020-11-28 09:52

When using the function atoi (or strtol or similar functions for that matter), how can you tell if the integer conversion failed or if the C-string

6条回答
  •  醉梦人生
    2020-11-28 10:28

    For C++11 and later:

    The go-to function for string-to-integer conversion is now stoi, which takes a string and returns an int, or throws an exception on error.

    No need for the verbose istringstream hack mentioned in the accepted answer anymore.

    (There's also stol/stoll/stof/stod/stold for long/long long/float/double/long double conversions, respectively.)

提交回复
热议问题