I have a string
which can be either a double
, float
or int
. I would like to convert the string
to the data type by making function calls. I am currently using functions such as stof
and stoi
which throw exceptions when the input is not a float
or int
. Is there another way to convert the strings without having to catch exceptions? Perhaps some function that passes a a pointer to a float
as argument and just returns a boolean
which represents the success of the function of call. I would like to avoid using any try
catch
statements in any of my code.

- 4,156
- 21
- 72
- 113
-
You can wrap `stoi` et al in your own functions and swallow the exceptions in there. – juanchopanza Jul 16 '14 at 15:58
-
I do not want to catch exceptions at all. So, I am looking for something that I can use without having to use try catch statements. – RagHaven Jul 16 '14 at 16:00
-
Implement your wrappers, then `try...catch` only exist in those wrapper functions. – timrau Jul 16 '14 at 16:01
-
I do not want to use try catch statements anywhere in my code. Hence I am looking for an API that does not throw exceptions. – RagHaven Jul 16 '14 at 16:04
-
Then you can use `atoi`, `atof` etc. – juanchopanza Jul 16 '14 at 16:04
-
In any case, you won't get around checking for errors and handling them. Even if you use the C-style functions `strtoX`, you'll need to add code to check whether your string actually contains an integer of floating point representation. The `strtoX` call doesn't suffice since you can't distinguish error from successful operation by the return value. – cmaster - reinstate monica Jul 16 '14 at 16:14
-
What should happen if the string doesn't contain a `int`/`float`/...? – sth Jul 16 '14 at 16:24
-
@cmaster-reinstatemonica "*The `strtoX` call doesn't suffice since you can't distinguish error from successful operation by the return value*" - true, but you can distinquish by examining `errno` instead, just as `std::stoX()` does when it calls `strtoX()` and has to decide when to `throw` an exception or not. – Remy Lebeau Jan 12 '21 at 23:53
-
@RemyLebeau Well, technically everything I said is perfectly correct. But I get your point. Yes, you can and should check `errno` when you use a `strtoX()` function, *because* the return value cannot signal the condition. You need to take something else (like `errno`) into account. A well-designed C function would return an error code and output the actual result via a pointer argument. And a flexible C function would additionally allow the user to specify what should be done to the result variable in case of a range error (write saturated value / write wrap-around value / don't write output). – cmaster - reinstate monica Jan 13 '21 at 00:18
3 Answers
Use a std::stringstream
and capture the result of operator>>()
.
For example:
#include <string>
#include <iostream>
#include <sstream>
int main(int, char*[])
{
std::stringstream sstr1("12345");
std::stringstream sstr2("foo");
int i1(0);
int i2(0);
//C++98
bool success1 = sstr1 >> i1;
//C++11 (previous is forbidden in c++11)
success1 = sstr1.good();
//C++98
bool success2 = sstr2 >> i2;
//C++11 (previous is forbidden in c++11)
success2 = sstr2.good();
std::cout << "i1=" << i1 << " success=" << success1 << std::endl;
std::cout << "i2=" << i2 << " success=" << success2 << std::endl;
return 0;
}
Prints:
i1=12345 success=1
i2=0 success=0
Note, this is basically what boost::lexical_cast
does, except that boost::lexical_cast
throws a boost::bad_lexical_cast
exception on failure instead of using a return code.
See: http://www.boost.org/doc/libs/1_55_0/doc/html/boost_lexical_cast.html
For std::stringstream::good, see: http://www.cplusplus.com/reference/ios/ios/good/
-
1I tried doing the same with wstringstream, because my string is actually a wstring, but I get an error saying cannot convert from 'std::basic_istream
>' to 'bool' – RagHaven Jul 16 '14 at 20:55 -
This solution does not differentiate between float double and int.. they all convert into each other as a success. – James Sep 30 '15 at 22:35
-
`bool success1 = sstr1 >> i1; // forbidden in c++11` - only because that is using an implicit type-cast for copy-initialization, but `istream::operator bool` is marked as `explicit`. So use an explicit type-cast instead to use direct-initialization, eg: `bool success1 = static_cast
(sstr1 >> i1);` – Remy Lebeau Jan 13 '21 at 00:02
To avoid exceptions, go back to a time when exceptions didn't exist. These functions were carried over from C but they're still useful today: strtod
and strtol
. (There's also a strtof
but doubles will auto-convert to float anyway). You check for errors by seeing if the decoding reached the end of the string, as indicated by a zero character value.
char * pEnd = NULL;
double d = strtod(str.c_str(), &pEnd);
if (*pEnd) // error was detected

- 299,747
- 42
- 398
- 622
-
Checking if `pEnd` reached a null terminator is the wrong way to check for failure. The entire string can be consumed properly, thus setting `pEnd` to point at the null terminator, but the function can still fail to convert the data to a `double` if the numeric value represented by the string is too large to fit in a `double`. You have to look at `errno` to detect a conversion failure. – Remy Lebeau Jan 12 '21 at 23:57
-
@RemyLebeau my experience with `errno` and different functions is that you can't rely on it as an error indicator, only to tell you what the error is once you've detected it by other means. Your concern about consuming the entire string but still encountering an error is valid, but I'm not sure of the best way to detect that. – Mark Ransom Jan 13 '21 at 01:35
-
A comprehensive implementation of error checking for the strto* family of functions can be found here: https://stackoverflow.com/a/26083517/863879 – Keith Morgan Sep 30 '22 at 22:56
Mark Ransom, you hit the nail on the head. I understand RagHaven because in certain situations exceptions are a nuisance, and converting alphanumeric chains to doubles should be something light and fast, not subject to the exception handling mechanism. I found that a five-alphanumeric string sorting algorithm took more than 3 seconds because exceptions were thrown in the process and somewhere in the software something was complaining.
In my search for conversion functions without launching exceptions I found this (I work with C++ Builder):
double StrToFloatDef(string, double def);
That function tries to return a float, and, if it does not succeed, instead of launching an exception it returns the value that is passed in the 2nd argument (which could for example be put to std::numeric_limits<double>::max())
. Checking if the return value matches 'def' you can control the result without exceptions.
Mark's proposal, std::strtod
, is just as good but much faster, standard and safe. A function like the one RagHaven asks for could look like this:
bool AsDouble(const char* s, double& v) const noexcept
{
char* pEnd = nullptr;
v = std::strtod(s, &pEnd);
return *pEnd == 0;
}

- 31
- 4