Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String to float using stringstream

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;
}
like image 296
Chef Flambe Avatar asked Oct 18 '12 05:10

Chef Flambe


2 Answers

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.

like image 196
john Avatar answered Oct 14 '22 17:10

john


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.

like image 40
Matthieu M. Avatar answered Oct 14 '22 18:10

Matthieu M.