Hi everyone. I'm trying to convert a string to a float but when I do it always goes positive. Right now someone types a string, and I check the first element for a negative but no matter what happens, it always turns it positive. What am I doing wrong?
If it starts with - (minus), you are converting it to a float, and then negating it. Negating a negative becomes a positive.
if it doesn't start with -, then you aren't negating it.
> returnedFloat = stof(floatNumber);
> returnedFloat = -returnedFloat;
Maybe stof() already knows how to deal with the negative, so making it negative again on the 2nd line just makes it positive.
#include <iostream>
#include <sstream>
#include <string>
usingnamespace std;
template<typename T> T getVal()
{
T val;
bool OK = false;
string str;
while( !OK )
{
cout << "Enter value: ";
getline( cin, str );
stringstream ss( str );
OK = ( ss >> val && !( ss >> str ) ); // a T and nothing but a T
}
return val;
}
int main()
{
float f = getVal<float>();
cout << "You entered " << f << '\n';
}
Can you elaborate on how yours works lastchance and why mine doesn't? I'm trying to understand what I was doing wrong? Is there a way to fix mine to work? I basically need to ensure someone is typing in a float. FYI, I'm using an online c++ compiler, in this case the one at onlinegdb.com
@kruuth,
You haven't given a whole code, so it's difficult to tell. However, @salem c thinks your code works, so that is OK by me.
I have to say, your code is rather difficult to read. In particular,
- if you use stof() then it will automatically return the right sign; you don't have to do anything about minuses. You could simply use return stof( str );
or you could simply input a float in the first place!
- most people looking at it would assume that floatOK goes true when all is OK; apparently, your code does the diametric opposite.
- similarly, most people would assume that floatNumber had type float; but in your code it has type string.
If you are using something online, particularly with a non-Windows PC, then it is just possible that what you think you are entering as a minus sign ... is actually some sort of hyphen.
Your code will accept "123-" or "1-234" or "1-800-222-1234". Let the library parse the number.
1 2 3 4 5 6 7 8 9
float f;
while (true) {
cout >> "Enter a number: ";
if (cin >> f) break;
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // That first argument is a really big number. Requires #include <limits>
cout >> "Invalid number\n";
}
// When you get here, f is valid
Actually you were spot on. I didn't realize I was printing the wrong value out. I had two variables, the pre and post value and I was printing pre on both cases.