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).
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Correctly parse PDF paragraphs with Python
- Why does const allow implicit conversion of refere
- thread_local variables initialization
相关文章
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- How do I get from a type to the TryParse method?
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
The C++ String Toolkit Library (StrTk) has the following solution:
The InputIterator can be of either unsigned char*, char* or std::string iterators, and T is expected to be a signed int, such as signed int, int, or long
You could use this defined method.
And if you were to convert from String to an Integer, you would just do the following.
The output would be 102.
If you have C++11, the appropriate solutions nowadays are the C++ integer conversion functions in
<string>
:stoi
,stol
,stoul
,stoll
,stoull
. They throw appropriate exceptions when given incorrect input and use the fast and smallstrto*
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.
You can use the a stringstream from the C++ standard libraray:
See Stream pitfalls for pitfalls of errorhandling and streams in C++.
You can use Boost's
lexical_cast
, which wraps this in a more generic interface.lexical_cast<Target>(Source)
throwsbad_lexical_cast
on failure.