I found this code online as a template for doing a string to float/int/double conversion. It's only here so I have something to reference for the question....
I want to have a user enter a number as a string, convert it to a float, test it for success and drop out if entry was 'Q' or print "Invalid input" if it wasn't the 'Q'uit character and return for more input.
What's the syntax for a conversion fail test? Would it be ss.fail() ?
// using stringstream constructors.
#include <iostream>
#include <sstream>
using namespace std;
int main () {
int val;
stringstream ss (stringstream::in | stringstream::out);
ss << "120 42 377 6 5 2000";
/* Would I insert an
if(ss.fail())
{
// Deal with conversion error }
}
in here?! */
for (int n=0; n<6; n++)
{
ss >> val;
cout << val*2 << endl;
}
return 0;
}
Your code isn't very helpful. But if I understand you right do it like this
string str;
if (!getline(cin, str))
{
// error: didn't get any input
}
istringstream ss(str);
float f;
if (!(ss >> f))
{
// error: didn't convert to a float
}
There's no need to use fail.
Actually, the simplest way to do string to float conversion is probably boost::lexical_cast
#include <string>
#include <boost/lexical_cast.hpp>
int main() {
std::string const s = "120.34";
try {
float f = boost::lexical_cast<float>(s);
} catch(boost::bad_lexical_cast const&) {
// deal with error
}
}
Obviously, in most cases, you just don't catch the exception right away and let it bubble up the call chain, so the cost is much reduced.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With