Reputation: 65
i am getting an problem
string ccc="example";
int cc=atoi(csession);
it says cannot convert ‘std::string’ to ‘const char*’ for argument ‘1’ to ‘int atoi(const char*)’
do i should convert the string to char array and then apply to atoi
or is there is any other way
Upvotes: 1
Views: 340
Reputation: 133112
istringstream in(ccc);
int cc;
in >> cc;
if(in.fail())
{
// error, ccc had invalid format, more precisely, ccc didn't begin with a number
//throw, or exit, or whatever
}
istringstream
is in header <sstream>
and in namespace std
. The above code will extract the first integer from the string that is, if ccc
were "123ac" cc
would be 123. If ccc
were "abc123" then cc
would have undefined value and in.fail()
would be true.
Upvotes: 3
Reputation: 229
According to your description, maybe what you want is:
string ccc="example"; int cc=atoi(ccc.c_str());
Upvotes: 2
Reputation: 10280
Hehe, nice one Armen. Here's a solution using boost::lexical_cast:
#include <boost/lexical_cast.hpp>
.
.
.
int c = boost::lexical_cast<int>(csession);
Documentation available here: boost::lexical_cast.
Upvotes: 1