raja
raja

Reputation: 65

converting string to integer problem in c++

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

Answers (4)

Armen Tsirunyan
Armen Tsirunyan

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

xueyumusic
xueyumusic

Reputation: 229

According to your description, maybe what you want is:

string ccc="example"; int cc=atoi(ccc.c_str());

Upvotes: 2

Daniel Lidstr&#246;m
Daniel Lidstr&#246;m

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

usta
usta

Reputation: 6869

Use .c_str() on the string object to pass it to atoi

Upvotes: 1

Related Questions