Monkeyanator
Monkeyanator

Reputation: 1416

Using C++ strings with C library functions

The error occurs when I try to use the atoi(const char*) function in the following line...

externalEncryptionRawHolder[u] = atoi(parser.next()); 

The 'parser' object is a string parser and the 'next' method returns a string. I think the error has something to do with the fact that the string within the 'atoi' function isn't a constant... but I'm not sure. The gist of the error is 'cannot convert string to const char *'. How can I make my string constant? Any help would be very appreciated (by the way, in case you're wondering what the index 'u' is, this is within a 'for' loop).

Upvotes: 2

Views: 152

Answers (2)

Drew Dormann
Drew Dormann

Reputation: 63947

string::c_str() will convert a string to a const char*, which is what atoi expects.

externalEncryptionRawHolder[u] = atoi(parser.next().c_str()); 

Upvotes: 1

Seth Carnegie
Seth Carnegie

Reputation: 75150

You have to call c_str() on the string object to get a const char*:

externalEncryptionRawHolder[u] = atoi(parser.next().c_str());

Note, though, that you should not do this:

const char* c = parser.next().c_str();

Because c will point to the memory that was managed by the string returned by parser.next(), which gets destroyed at the end of the expression, so then c points to deallocated memory. The first example is ok though because the string is not destroyed until after atoi has returned.

Upvotes: 7

Related Questions