2

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).

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

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

3 Comments

Thanks so much! I'll thank you as soon as able (7 minutes). Say, why does that work?
@Monkeyanator just because next() returns a string which is incompatible with what the function atoi expects, which is a const char*. string has a member function c_str() though, which returns a const char* to the string it manages internally, which atoi can work with
@Monkeyanator: Seth is right. string and char* can both represent text, but they aren't the exact same thing. This works because you're converting one form to the other.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.