I'm trying to figure out how to use the atoi function I have wrote and understand this so far:
#include<iostream>
#include<cstdlib>
#include<cstring>
using namespace std;
int main()
{
int x;
string str="34";
x=atoi(str);
cout<<x;
system("pause");
return 0;
}
And Then I get error reports about a freakin const char?! HELP!

Recommended Answers

the string::c_str() method converts the contents of an std::string to const char*. For example:

string str1 = "Hello";
const char* str2 = "Hello";
str1.c_str();//would return a value equivalent to str2

further information here

You'd be better off using …

Jump to Post

All 4 Replies

Always post the exact errors you get for the best help.

atio() takes input of type const char* .

do this:

x=atoi(str.c_str());

Or, better yet, use stringstreams:

#include <sstream>
using namespace std;

int main()
{
    stringstream ss;
    int x;
    string str = "34";
    ss << str;
    ss >> x;

    return 0;
}

Thank you so much-it works now but I still don't get why you need the .c_str()-does it make it refer to str as a constant string?

the string::c_str() method converts the contents of an std::string to const char*. For example:

string str1 = "Hello";
const char* str2 = "Hello";
str1.c_str();//would return a value equivalent to str2

further information here

You'd be better off using string streams though. there isn't a need to convert an std::string into an old C-string (const char*). string streams can handle std::strings and C-strings.

commented: Say yes to string streams, no to atoi +20

Thank you.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.20 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.