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

C

CoreyWhite

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!
 
V

Victor Bazarov

David said:
On 5 Apr 2007 11:57:48 -0700 in comp.lang.c++, "CoreyWhite"

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

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top