954,483 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

string to integer OR float

Hi,

I was wondering if its possible to get the integer OR float value of a string. If I know it's an integer I can do int x = atoi(str) and atof if its a float but what do I do if I don't know what it is (in other words if I don't know if it's a float or an integer)?

Basically I have a string with two numbers (and a space between them) and I want to get the numbers, add them and print the result. (I know how to split the string)

Any ideas on that will be great. Thanks :)

obscured47
Light Poster
28 posts since Apr 2007
Reputation Points: 10
Solved Threads: 1
 

I would not use atoi or atof, I would use istringstream, with std::strings

Alternatively see below, it may be of use?
http://faq.cprogramming.com/cgi-bin/smartfaq.cgi?answer=1043372399&id=1043284385

iamthwee
Posting Expert
5,950 posts since Aug 2005
Reputation Points: 1,543
Solved Threads: 439
 

Why worry if the input is integer or floating point? Treat all as floating point and you have no problems.

vmanes
Posting Virtuoso
1,914 posts since Aug 2007
Reputation Points: 1,268
Solved Threads: 228
 

vmanes is right..

still if you want to keep both of them (i.e. int and float) then you may check for the '.' decimal in the string using iterators or anything else to traverse the string....

rajatC
Junior Poster
109 posts since Dec 2007
Reputation Points: 14
Solved Threads: 7
 

What about 1e7 ?

Duoas
Postaholic
2,043 posts since Oct 2007
Reputation Points: 1,140
Solved Threads: 229
 

I thought hacker speak wasn't allowed/permitted/desired here?

(Sorry, couldn't resist ;). I know your example is an exponential form, but it looks like....)

vmanes
Posting Virtuoso
1,914 posts since Aug 2007
Reputation Points: 1,268
Solved Threads: 228
 
What about 1e7 ?

didnt get you???I thought hacker speak wasn't allowed/permitted/desired here?

(Sorry, couldn't resist ;). I know your example is an exponential form, but it looks like....)

didnt get you too???

rajatC
Junior Poster
109 posts since Dec 2007
Reputation Points: 14
Solved Threads: 7
 

lol thanks for the replies I'll make them floats and play around with the decimals

obscured47
Light Poster
28 posts since Apr 2007
Reputation Points: 10
Solved Threads: 1
 

LOL :icon_lol:

RajatC Read here and here .

The joke is that the floating-point number 10,000,000, written as "1e7", looks like leetspeak.

This is a forum for programmers and hackers , not script kiddies and warez wannabies, so leetspeek is expressly verboten.

Duoas
Postaholic
2,043 posts since Oct 2007
Reputation Points: 1,140
Solved Threads: 229
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You