\$8

### Image of the Day Submit

IOTD | Top Screenshots

### The latest, straight to your Inbox.

Subscribe to GameDev.net's newsletters to receive the latest updates and exclusive content.

Sign up now

## C++ String to a number

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

22 replies to this topic

### #1Chad Smith  Members

Posted 14 March 2013 - 02:37 PM

I was working on my own function that would convert a string to a number, be it int, float, double or any of those built in data types.

Anyway writing the function is very easy and I do have it working properly.  My Question though is more a long the lines of dealing with when the string is not a number.  Currently I just build a stringstream on the string entered.  I then check to see if I can extract the data in the string stream into the number.  If not I just set it to 0 and return the number.  This works and if I enter a non number it returns 0.  Though is their a better way of doing this?

I ask this because since 0 could easily be a valid number I wouldn't ever know if it was a valid 0 or if returned 0 based on the fact that it was an error.  How would y'all do this?  Just have it return 0?

I did also think about passing in the number with the string by reference and returning a boolean value if it could do the conversion.

Thanks if someone could explain the "best" or "correct" way of doing this and checking the conversion.

### #2SiCrane  Moderators

Posted 14 March 2013 - 02:43 PM

Some other options: return a struct, pair or tuple that contains both an error code and the result of conversion; return the conversion but throw an exception on bad input; just use boost::lexical_cast instead and so on.

For error checking you might also want to check the situation where the first part of the string is a valid number but the rest isn't. Ex: "100fred"

### #3Servant of the Lord  Members

Posted 14 March 2013 - 02:52 PM

If you're using C++11, you can use std::to_string() to convert most basic types to a string, and std::stoi() (string to int) std::stof() (string to float), and related functions.

Are you really needing to check the output? If so, returning a bool and taking the result as a parameter is a good option.

You could also return a constant for invalid input: (std::numeric_limits<int>::max() or similar for ints, and NaN for floats). With NaN, this is a good option, but with integers, you'll have to be sure to check the result before doing any operations.

You might also want to balidate and convert the input as soon as possible, to isolate invalid input at the doorways to your program.

Edited by Servant of the Lord, 14 March 2013 - 02:59 PM.

It's perfectly fine to abbreviate my username to 'Servant' or 'SotL' rather than copy+pasting it all the time.
All glory be to the Man at the right hand... On David's throne the King will reign, and the Government will rest upon His shoulders. All the earth will see the salvation of God.
Of Stranger Flames -

### #4Chad Smith  Members

Posted 14 March 2013 - 03:18 PM

Thanks.  As soon as I posted this I remembered the C++11 functions so I went to the documentation to see about what it would return if the conversion wasn't possible.  I would more than likely use the C++11 in a true project, though I am writing some helper functions to just help me with some university projects.  The submission system compiler doesn't support a lot of C++11 right now it seems.  I will more than likely just throw an exception if the conversion could not be preformed.

Thanks SiCrane on the suggestion for checking if the rest of the string is a valid number also.  I actually did write a helper function already that loops through every character of the string to see if it is a valid char for a number (0-9, negative sign, or a decimal).  Also, just for learning and getting better: is their a better way to do it?  It would just seem on computers these days since a numerical string more than likely wouldn't be very long that it wouldn't take long to just loop through every character and checking each character while they are still valid numerical characters.

Edited by Chad Smith, 14 March 2013 - 03:26 PM.

### #5SiCrane  Moderators

Posted 14 March 2013 - 03:36 PM

Since you're using a stringstream you can just use rdbuf()->in_avail() after you extract the number. If in_avail() returns true, then there's stuff left in the buffer, which means that part of it didn't parse as a number. This assumes that you've already stripped out the whitespace anyways.

### #6jellyfishchris  Members

Posted 14 March 2013 - 07:01 PM

From what I gather you might want to consider using std::throw instead of returning a value.

### #7SiCrane  Moderators

Posted 14 March 2013 - 07:13 PM

throw is a keyword, it doesn't live in namespace std.

### #8EddieV223  Members

Posted 14 March 2013 - 07:33 PM

if you don't have c++11, no problem, you can use the atoi function.

It takes a c string as parameter returns an int, if you have a std::string just do

int myInt = atoi( myString.c_str() );

http://en.cppreference.com/w/cpp/string/byte/atoi

Edited by EddieV223, 14 March 2013 - 07:41 PM.

If this post or signature was helpful and/or constructive please give rep.

// C++ Video tutorials

http://www.youtube.com/watch?v=Wo60USYV9Ik

// Easy to learn 2D Game Library c++

SFML2.2 Download http://www.sfml-dev.org/download.php

SFML2.2 Tutorials http://www.sfml-dev.org/tutorials/2.2/

// Excellent 2d physics library Box2D

http://box2d.org/about/

// SFML 2 book

http://www.amazon.com/gp/product/1849696845/ref=as_li_ss_tl?ie=UTF8&camp=1789&creative=390957&creativeASIN=1849696845&linkCode=as2&tag=gamer2creator-20

### #9jellyfishchris  Members

Posted 14 March 2013 - 08:08 PM

Sorry I was thinking of throw std::bad_alloc

### #10Chad Smith  Members

Posted 14 March 2013 - 08:15 PM

if you don't have c++11, no problem, you can use the atoi function.

It takes a c string as parameter returns an int, if you have a std::string just do

int myInt = atoi( myString.c_str() );

http://en.cppreference.com/w/cpp/string/byte/atoi

Yea I know, thanks though.  it's for both University Projects and to teach myself.  It had been a while since I've worked exclusively with C++ so I wanted to try to get myself used to working with std::stringstreams again.

Since you're using a stringstream you can just use rdbuf()->in_avail() after you extract the number. If in_avail() returns true, then there's stuff left in the buffer, which means that part of it didn't parse as a number. This assumes that you've already stripped out the whitespace anyways.

Thanks!  I'll have to do some quick research on that function!  I'll look into it now!

Thanks everyone!  Just wanted to learn some other and/or better ways to do some quick things.  Thanks for the suggestions!

Edited by Chad Smith, 14 March 2013 - 08:19 PM.

### #11SiCrane  Moderators

Posted 15 March 2013 - 06:35 AM

Sorry I was thinking of throw std::bad_alloc

Why would you throw std::bad_alloc, the exception meant for memory allocation failure, for not being able to parse a string?

### #12Servant of the Lord  Members

Posted 15 March 2013 - 12:17 PM

I think he just means throw an exception in general.

If one was to be thrown, an std::runtime_error would be better. Perhaps a custom 'my::bad_conversion' or 'my::bad_parse' exception used by all your conversion functions, that inherits from std::runtime_error.

However, passing in non-conforming data into StringToX type functions aren't really exceptional behavior, IMO - but I suppose that depends on the project.

It's perfectly fine to abbreviate my username to 'Servant' or 'SotL' rather than copy+pasting it all the time.
All glory be to the Man at the right hand... On David's throne the King will reign, and the Government will rest upon His shoulders. All the earth will see the salvation of God.
Of Stranger Flames -

### #13Mathimetric  Members

Posted 15 March 2013 - 12:27 PM

EDITED DUE TOO THE COMMENT BELOW FROM MODERATION:

ABOUT THE PROGRAM' MEMORY LEAK; (FIX)

did you try checking the string[Lvalue] characters by using...

<ctype.h>

int _RTLENTRY _EXPFUNC isalnum (int __c);
int _RTLENTRY _EXPFUNC isalpha (int __c);
int _RTLENTRY _EXPFUNC iscntrl (int __c);
int _RTLENTRY _EXPFUNC isdigit (int __c);
int _RTLENTRY _EXPFUNC isgraph (int __c);
int _RTLENTRY _EXPFUNC islower (int __c);
int _RTLENTRY _EXPFUNC isprint (int __c);
int _RTLENTRY _EXPFUNC ispunct (int __c);
int _RTLENTRY _EXPFUNC isspace (int __c);
int _RTLENTRY _EXPFUNC isupper (int __c);
int _RTLENTRY _EXPFUNC isxdigit(int __c);
int _RTLENTRY _EXPFUNC isascii (int __c);

you could use these to maybe determine if you have a number or not.

you could also try being more specific to handling the errors by using a pointer return value

such as

typedef <type> number_;

//(EDIT)/////////////////////////////////////////////////////////////////

// pointer rtn is givin a static address only 1 time so there is no memory leaks'

//

number_ * stringtonum(string_type  *)

{

static number_ * rtn;

if( rtn == NULL){ rtn = new number_[2]; }

//where rtn[0] == error handle , rtn[1] == converted num

//.........do conversion block ..............///

return rtn;  //return address to variable rtn

}

example impliment:

#define out<<        ....

#define error_       ....

if(   (*(stringtonum(data)+0)) ) out<<error_; //is there an error in rtn?

else

assign = (*(stringtonum(data)+1));

///edited to ocommidate  the BELOW COMMENT

///there is no leak if the return type is givin a static address -> to point too

Edited by Mathimetric, 09 January 2014 - 11:30 AM.

### #14SiCrane  Moderators

Posted 15 March 2013 - 12:55 PM

That's really a horrible idea. If you're going to return a pair for error code and conversion result, then don't use dynamic allocation for it. Your own sample code leaks memory from using this kind of interface and calls the function twice to see if there's a conversion error.

### #15superman3275  Members

Posted 15 March 2013 - 01:04 PM

You can also use String-Streams!

Cheers !

(Sorry, OP was already using them!)

Edited by superman3275, 17 March 2013 - 04:16 PM.

I'm a game programmer and computer science ninja !

Here's my 2D RPG-Ish Platformer Programmed in Python + Pygame, with a Custom Level Editor and Rendering System!

Here's my Custom IDE / Debugger Programmed in Pure Python and Designed from the Ground Up for Programming Education!

Want to ask about Python, Flask, wxPython, Pygame, C++, HTML5, CSS3, Javascript, jQuery, C++, Vimscript, SFML 1.6 / 2.0, or anything else? Recruiting for a game development team and need a passionate programmer? Just want to talk about programming? Email me here:

hobohm.business@gmail.com

or Personal-Message me on here !

### #16Chad Smith  Members

Posted 15 March 2013 - 10:23 PM

You can also use String-Streams!

Cheers !

I already am to do the conversion?  I thought I mentioned that in my first post.

If you just do the conversion with a stringstream and extract the number out of the string that isn't a pure number then the number will be filled with garbage

Quick example: if the the string we tried to convert was "abc20" then the number will be filled with garbage.  To me that then would need to require a check to make sure the conversion is possible at first so the number isn't filled with garbage.

Also I really do agree with Servant in that a "StringToX" function really isn't exceptional behavior.  Though it seems most of the library functions I see that do this throw an exception.  I do have it working by just throwing an exception if it couldn't do the conversion.  I then wrote another quick that just did the conversion and in a program would only do the conversion if the string was a number:

std::string myNumber = "20 abc";
int number = 0;

if(IsNumber(myNumber))
number = ToNumber<int>(myNumber);



that way the conversion only happens if I know it is a number.  Though while this may work just fine in my own little projects for a university, I don't think this is very safe for other users.  It seems it would force the users to always check before they tried the conversion and would require the users to create their own way of dealing with and error like that.

Though maybe I'm over thinking it?

### #17Servant of the Lord  Members

Posted 15 March 2013 - 10:48 PM

std::string myNumber = "20 abc";
int number = 0;

if(IsNumber(myNumber))
number = ToNumber<int>(myNumber);


that way the conversion only happens if I know it is a number.  Though while this may work just fine in my own little projects for a university, I don't think this is very safe for other users.  It seems it would force the users to always check before they tried the conversion and would require the users to create their own way of dealing with and error like that.

Not to mention that for every conversion, you have to iterate over the string twice instead of validating and converting at the same time ().

It's perfectly fine to abbreviate my username to 'Servant' or 'SotL' rather than copy+pasting it all the time.
All glory be to the Man at the right hand... On David's throne the King will reign, and the Government will rest upon His shoulders. All the earth will see the salvation of God.
Of Stranger Flames -

### #18Dragonsoulj  Members

Posted 15 March 2013 - 10:48 PM

T ConvertNumber(string numberStringToConvert, bool &wasANumber)

Return your number however you return it, and set your boolean to true if it was a number.

### #19Chad Smith  Members

Posted 15 March 2013 - 11:11 PM

std::string myNumber = "20 abc";
int number = 0;

if(IsNumber(myNumber))
number = ToNumber<int>(myNumber);


that way the conversion only happens if I know it is a number.  Though while this may work just fine in my own little projects for a university, I don't think this is very safe for other users.  It seems it would force the users to always check before they tried the conversion and would require the users to create their own way of dealing with and error like that.

Not to mention that for every conversion, you have to iterate over the string twice instead of validating and converting at the same time ().

Even though I didn't know a name for it I was thinking that it would have to iterate over the string twice.

T ConvertNumber(string numberStringToConvert, bool &wasANumber)

Return your number however you return it, and set your boolean to true if it was a number.

That's a solution that I really didn't think of.  Thanks for listing another solution.

Ok, i just wanted to post another solution I did.  What would you change?  What should be better?  I know it isn't nearly the best solution.

IsNumber Function

bool IsNumber(const std::string& text)
{
// const iterator to iterate through the string
std::string::const_iterator it = text.begin();

std::locale loc;

// while we have not reached the end of the string and the character we are on is a digit
// negative sign, or decimal point
while(it != text.end() && (std::isdigit(*it, loc) || *it == '-' || *it == '.'))
{
it++;
}

return !text.empty() && it == text.end();
}


ToNumber

// ToNumber
// Takes in a string to convert to a number
// Checks to make sure that the string is a number before converting
// sets validNumber to true if it can convert, false otherwise
// Return Type Element to convert the string to any number
template <typename Element>
Element ToNumber(const std::string& text, bool& validNumber)
{
Element number = 0;

// If the string is a number, validNumber is true, otherwise false
(IsNumber(text)) ? (validNumber = true) : (validNumber = false);

// Only do the conversion if we have a validNumber;
if(validNumber)
{
// istringstream buffer to hold the string passed in
std::istringstream buffer(text);
// extract the number from the buffer
buffer >> number;
}

return number;
}


I still feel it could be a lot better.  I am still not a fan of the IsNumber Function.  I feel it could be a bit too confusing to follow for something that is so simple.

So couple questions:

1: Better solution?  As in am I still over thinking this?

2: is it right to use the c++ std::isdigit function here that takes the std::locale?  I saw an example using it and after trying to read about the std::locale I wasn't 100% sure what I was doing exactly.

3: Bad use of the Conditional Ternary Operator?  I know what it is saying just fine and I felt a full if/else statement was too long here for something really simple.  Though would this be by chance considered abusing the operator?

Maybe I just need to get over always using the full if/else with the curly braces on something that simple (I for some reason do a double take every time the curly braces aren't used on those one liners if/else statements, yet I read the conditional operator just fine almost always).

Edited by Chad Smith, 16 March 2013 - 01:40 AM.

### #20SiCrane  Moderators

Posted 16 March 2013 - 07:15 AM

First basic problem is that your IsNumber() function works the same for every single number type, but not every number type has the same valid format. What's a valid float is not necessarily a valid int. Secondly, you're only looking at valid characters without looking at the pattern of characters. IsNumber() would return true for "....." but this isn't a valid number for any data type. Next, if you're going to bring in a locale, then you should be looking at valid number formats for the given locales. For instance "10,000" is a valid formatted integer with a thousands separator for en-US, but the same number number formatted for de-DE is "10.000" neither of which would be parsed by std::stringstream properly as an integer. IsNumber() also misses the exponent portion of a float which generally starts with an "e" or "E". Also being a properly formatted number doesn't mean that the conversion would succeed. For instance, what happens when you want to format "10000000000000000000000000000" into a 32-bit int?

The ternary operator can be replaced very simply with validNumber = IsNumber(text);.

But again, the whole IsNumber() logic is simply duplicating the work std::stringstream already does when parsing the number itself. It would be less work, both in terms of programmer effort and in clock cycles at run time, and less bug prone to just to check the state of the stream after extraction.

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.