Reputation: 419
I've tried many ways, as detailed in here: http://www.cplusplus.com/forum/general/13135/
Most of them work if I run the file on Windows, but when I try to do so on LINUX, none of them works. For example, I try to do:
string str = "123";
int sp;
istringstream ( str ) >> sp;
But it gives me the error: "invalid use of incomplete type ‘struct std::istringstream’ /usr/include/c++/4.4/iosfwd:67: error: declaration of ‘struct std::istringstream’"
Other option was 'atoi', but it says that 'atoi was not defined in this scope.'
Any ideas why its happening?
Upvotes: 2
Views: 5411
Reputation: 25386
The POSIX way to covert std::string
to int
will be atoi()
#include <cstdlib>
...
string str = "123";
int sp = atoi( str.c_str() );
If you want to convert not only to int
but to many types, it is better to use stringstream
. However, beware the increased compilation time.
Upvotes: 3
Reputation: 593
as for the atoi() function, you need to include the cstdlib (#include <cstdlib>
) header.
then you can use it like this:
string str= "123";
int sp = atoi(str.c_str());
it will tell the string object to act as a const char* pointing to a C-style string (most probably best known as a string with the zero terminator \0).
Upvotes: 5