How can I convert a string into an integer? I tried this: totalMins += atoi(MovieRecord->getMinutes()); Which I think only works for C-strings, and I tried this: totalMins += static_cast<int>(MovieRecord->getMinutes()); which I think only works for converting an int to a double or something similar.

3 Years
Discussion Span
Last Post by rookieNeedsHelp

atoi does indeed only work with cstrings, however you can convert an std::string to a cstring using .c_str(). So for your example I would guess that the solution is:

totalMins += atoi(MovieRecord->getMinutes().c_str()); 

Depending on your need, you may also want to look at strtol which has better error-checking support than atoi and can handle a larger variety of input.


I tend to go for the stringstream class instead, because it is more "C++-style" and it has more options in terms of formatted input. For a simple string-to-int mechanism, I would just do:

std::stringstream(MovieRecord->getMinutes()) >> totalMins;

Or, in two steps:

std::stringstream ss(MovieRecord->getMinutes());
ss >> totalMins;

This is also nice because any type that can be read from / written to a standard stream can now be converted to / from a string, via the string-stream.

For a simple conversion, the C version is definitely shorter, but I still tend to use the string-stream version regardless, just for uniformity with the cases where the string-stream is definitely better (more flexible / generic).

N.B.: When you use C standard functions, like atoi, in C++, you still need to qualify them with the std namespace, e.g., as std::atoi (or through a using statement). Many compilers provide the C functions in the global scope, but that is not a requirement, and so, for portability, remember that they are in the std namespace.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.