View Single Post
Old Dec 8th, 2005, 11:58 PM   #2
grumpy
Programming Guru
 
grumpy's Avatar
 
Join Date: Jun 2005
Location: Adelaide, South Australia
Posts: 1,223
Rep Power: 5 grumpy is on a distinguished road
I assume you want to convert a string like "42" into the value 42.

In vanilla C, this would be done by;
#include <stdlib.h>

int main()
{
    const char v[] = "42";
    int x;
    x = atoi(v);
}
That is deprecated in C++ (i.e. it is allowed, but discouraged and may be removed from a future C++ standard). The C++ equivalent would be;
#include <string>
#include <cstdlib>

int main()
{
    std::string v("42");
    int x;
    x = std::atoi(v.c_str());
}
If you want to do more complex things then you have a few choices, such as;

sscanf() is a C function that reads data from a C-style string

in C++, look up the ostringstream class. An example of it's usage follows;
#include <string>
#include <sstream>
#include <ostream>

int main()
{
    std::string v("42");
    std::ostringstream str(v);
    int x;
    str >> x;   // will get value 42
}
E&OE: I've written the above examples quickly, so may have introduced minor errors. You can also remove the need for "std::" prefixes by judicious use of "using namespace std;", but I prefer code that is guaranteed not to be ambiguous.
grumpy is offline   Reply With Quote