How to parse a string to an int in C++?

前端 未结 17 1731
忘了有多久
忘了有多久 2020-11-21 11:01

What\'s the C++ way of parsing a string (given as char *) into an int? Robust and clear error handling is a plus (instead of returning zero).

17条回答
  •  执念已碎
    2020-11-21 11:59

    If you have C++11, the appropriate solutions nowadays are the C++ integer conversion functions in : stoi, stol, stoul, stoll, stoull. They throw appropriate exceptions when given incorrect input and use the fast and small strto* functions under the hood.

    If you are stuck with an earlier revision of C++, it would be forward-portable of you to mimic these functions in your implementation.

提交回复
热议问题