Click here to Skip to main content
15,891,184 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I accidentally deleted the bit of my code, that turns a string into a double, I rewrote it but it doesn't do what I want it to, and I forgot how this is new code bit:
double str2int(string test)
{
double qtest;
stringstream etest;
etest << test;
etest >> qtest;
cout<<qtest<<endl;
return qtest;
}

it works but doesn't convert stuff like a5 into a double?
ways to do that?
sorry for the rushed nature of this question, I have a bus to catch haha

What I have tried:

i've tried rewriting the code but it just gives the same result
Posted
Updated 2-Mar-22 20:50pm
Comments
_Asif_ 3-Mar-22 3:01am    
as everyone mentioned "a5" is not double type.
"5" -> 5.00 because 5 as string can be converted into double as 5.00
But how "a" in "a5" will be converted into double?

You can't turn a string like "a5" into a double: it isn't a numeric value at all, and will throw an error in nearly every language, including C++.

To do that, you'd have to "strip out" the non-numeric data and convert that, but first think about the input value range and work out exactly what you want to convert it to.
For example, "a5p6" : what should that be? 56? 5.6? 6? 5? What about "5e6"? Should that be 5000000? Or 56? How about "e5"? Is that 5 or zero?

THink about where you get your data from and what it might actually represent: normally a "string based value" is a string for a reason!
 
Share this answer
 
Comments
CPallini 3-Mar-22 2:29am    
'a5' is the bus no.
OriginalGriff 3-Mar-22 2:42am    
Could be: it really isn't clear from the OP question. :sigh:
The input value: a5 is not a valid argument to convert into double. It should throws an exception "invalid_argument"
Check the following link for conversion from string to double/float.
C++ String to float/double and vice-versa[^]
 
Share this answer
 
Comments
Abdulrahmon Tijani 3-Mar-22 0:35am    
as a string
also I'm not using stoi/stod(you know them) so it doesn't give an error
No big deal: simply use the stod of the standard library.

tip: check for the error cases
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900