String to float using string stream

I found this code online as a template to execute a string for float / int / double conversion. This is only here, so I have something to link to the question ....

I want the user to enter a number as a string, convert it to a float, check it for success and drop out if the entry was "Q" or "Invalid input" if it was not "Q", uit and return for more input.

What is the syntax for a test with a conversion error? Will 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; } 
+7
source share
3 answers

Your code is not very useful. But if I understand that you're right, do it like that.

 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 } 

No need to use glitch.

+9
source

In fact, the easiest way to convert a string to a float 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 simply do not catch the exception right away and do not start the call chain, so the cost is significantly reduced.

+2
source

Some of the features asked by the original question are as follows:

  • output twice the value of the input floats
  • Report invalid entries
  • continue searching for floats even after detecting invalid inputs
  • stop after viewing the character "Q"

I think the following code satisfies the above query:

 // g++ -Wall -Wextra -Werror -static -std=c++11 -o foo foo.cc #include <iostream> #include <sstream> void run_some_input( void ) { std::string tmp_s; int not_done = 1; while( not_done && getline( std::cin, tmp_s ) ) { std::stringstream ss; ss << tmp_s; while( ! ss.eof() ) { float tmp_f; if ( ss >> tmp_f ) { std::cout << "Twice the number you entered: " << 2.0f * tmp_f << "\n"; } else { ss.clear(); std::string tmp_s; if( ss >> tmp_s ) { if( ! tmp_s.compare( "Q" ) ) { not_done = 0; break; } std::cout << "Invalid input (" << tmp_s << ")\n"; } } } } } int main( int argc __attribute__ ((__unused__)), char **argv __attribute__ ((__unused__)) ) { run_some_input(); } 

Here is an example session:

 $ ./foo 1 Twice the number you entered: 2 3 4 Twice the number you entered: 6 Twice the number you entered: 8 5 bad dog Quit 6 8 Q mad dog Twice the number you entered: 10 Invalid input (bad) Invalid input (dog) Invalid input (Quit) Twice the number you entered: 12 Twice the number you entered: 16 
0
source

All Articles