954,500 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

HELP!! how do you use atoi?

I'm trying to figure out how to use the atoi function I have wrote and understand this so far:
#include
#include
#include
using namespace std;
int main()
{
int x;
string str="34";
x=atoi(str);
cout<

CPPRULZ
Junior Poster in Training
91 posts since Aug 2008
Reputation Points: 10
Solved Threads: 0
 

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;
}
CoolGamer48
Posting Pro in Training
401 posts since Jan 2008
Reputation Points: 77
Solved Threads: 40
 

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?

CPPRULZ
Junior Poster in Training
91 posts since Aug 2008
Reputation Points: 10
Solved Threads: 0
 

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.

CoolGamer48
Posting Pro in Training
401 posts since Jan 2008
Reputation Points: 77
Solved Threads: 40
 

Thank you.

CPPRULZ
Junior Poster in Training
91 posts since Aug 2008
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You