# OO C++ Workshop: Converting a String to a Numeric Type

Discussion in 'C++' started by CoreyWhite, Apr 5, 2007.

1. ### CoreyWhiteGuest

Problem:
You have numbers in string format, but you need to convert them to a
numeric type, such as an int or float.

Solution:

You can do this with the standard library functions. The functions
strtol, strtod, and strtoul, defined in <cstdlib>, convert a null-
terminated character string to a long int, double, or unsigned long.
You can use them to convert numeric strings of any base to a numeric
type (Even hexidecimal). The code I wrote here demonstrates this
function, within an object oriented design model. You can use it for
converting hexadecimal strings to a long integer.

I'll also include the non-object oriented code so you can see how this
can be done without using many of the great tools in C++, as the point
of this workshop is to compare object oriented algorithms to standard
C code.

#include <iostream>
#include <string>
#include <vector>
#include <cstdlib>

using namespace std;

class Hex : public vector<string>
{

public:
Hex() {
cout << "Converting hexadecimal strings to integers."<<endl<<endl;
}
inline void operator()(const string &hexStr)
{
push_back(hexStr);
}

inline int operator[](const int &n)
{
string hexStr = at(n);

char *offset;
if (hexStr.length() >2){
if (hexStr[0] == '0' && hexStr[1] == 'x') {
return strtol(hexStr.c_str(), &offset, 0);
}
}
return strtol(hexStr.c_str(), &offset, 16);

}

};

int main( void ) {
Hex myHex;
myHex("0x12AB");
myHex("12AB");
for(int cnt=0; cnt < myHex.size(); cnt++){
cout << myHex[cnt] << endl;
}

return 0;
}

==================
ANOTHER PROGRAM
==================

#include <iostream>
#include <string>
#include <cstdlib>

using namespace std;

long hex2int(const string& hexStr) {
char *offset;
if (hexStr.length() > 2 ) {
if ( hexStr[0] == '0' && hexStr[1] == 'x' ) {
return strtol(hexStr.c_str(), &offset, 0 );
}
}
return strtol(hexStr.c_str(), &offset, 16);
}

int main(){
string str1 = "0x12AB";
cout << hex2int(str1) << endl;
string str2 = "12AB";
cout << hex2int(str2) << endl;
return 0;
}

=======
END
======

The program should output the hexidecimal number converted to 4779,
twice!!!

Hope you enjoy, and if you have any questions about my object oriented
design model, and I would be glad to explain what I am doing with it!

CoreyWhite, Apr 5, 2007

2. ### David HarmonGuest

On 5 Apr 2007 11:57:48 -0700 in comp.lang.c++, "CoreyWhite"
<> wrote,
>Newsgroups: alt.magick,alt.native,alt.religion.wicca,comp.lang.c++

David Harmon, Apr 6, 2007

3. ### Victor BazarovGuest

David Harmon wrote:
> On 5 Apr 2007 11:57:48 -0700 in comp.lang.c++, "CoreyWhite"
> <> wrote,
>> Newsgroups: alt.magick,alt.native,alt.religion.wicca,comp.lang.c++

It's time for folks to stop feeding that troll until she learns
to use Usenet properly.

Victor Bazarov, Apr 6, 2007