C++ String to a number

Started by
21 comments, last by Chad Smith 11 years, 1 month ago

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.

Advertisement
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"

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.

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.

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.

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

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

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

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

Sorry I was thinking of throw std::bad_alloc

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!

This topic is closed to new replies.

Advertisement