Jump to content
  • Advertisement
Sign in to follow this  
bartiss

How to convert char[] to a number? (C++)

This topic is 4823 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi, Is there a built-in function that converts a string to a number? For example: char "200" -> int 200 char "1.5" -> float 1.5 I know I can make myself one, but I'm sure somebody's done it ages ago :) Thanks Bartiss

Share this post


Link to post
Share on other sites
Advertisement
"Simple way"? How hard is boost::lexical_cast< float >(string)? Besides if boost::lexical_cast fails then it throws an exception which can be caught and you can carry on and try to recover from the error. If atoi or atof fail then BANG! Undefined behaviour. You're dead.

If you want to do the conversion without using boost or a stream and still detect errors then you need to use strtol or strtof and pass them the address of a pointer which you must then check against the end of input to ensure that the input was fully converted (otherwise the string "13*7" will successfully parse as 13).

Enigma

Share this post


Link to post
Share on other sites
Actually atoi() will return 0 if it can't process the string, so it's actually somewhat worse than undefined behavior because you don't know if it actually had a 0 or was an invalid value.

Share this post


Link to post
Share on other sites
Are you sure about that? The final draft standard for C99 states:
Quote:
C99 Final Draft Standard, Section 7.20.1, Paragraph 1:
The functions atof, atoi, atol, and atoll need not affect the value of the integer expression errno on an error. If the value of the result cannot be represented, the behavior is undefined.

Or am I reading that wrong?

Enigma

Share this post


Link to post
Share on other sites
You can do that with sscanf: http://www.cplusplus.com/ref/cstdio/sscanf.html


int n1;
float n2;
sscanf ("12","%i",&n1);
sscanf ("1.5","%d",&n2);


Bas

Share this post


Link to post
Share on other sites
Go with the std::stringstream approach (unless you have boost installed).

All of the other approaches have catches that may not be apparent on first glance.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!