stringstream使用方法将字符串转换为浮点数

7
我在网上找到了一个用于将字符串转换为浮点数/整数/双精度的代码示例,只是作为问题参考......
我想让用户输入一个数字作为字符串,将其转换为浮点数,测试其是否成功,如果输入为'Q'退出或如果不是'Q'字符则打印"无效输入"并返回更多输入。
如何进行转换失败测试?是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;
}

你遇到了什么语法错误? - Muthu Ganapathy Nathan
3个回答

9

您的代码并不是很有用。但如果我理解正确,可以这样做:

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
}

不需要使用fail。


2

实际上,将字符串转换为浮点数的最简单方法可能是使用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
    }
}

显然,在大多数情况下,您并不会立即捕获异常并将其传递到调用链中,因此成本大大降低。


0

原始问题中要求的一些功能包括:

  1. 输出输入浮点数的两倍
  2. 报告无效输入
  3. 即使遇到无效输入也要继续查找浮点数
  4. 在看到字符“Q”后停止

我认为以下代码满足上述要求:

// 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();
}

以下是一个示例会话:

$ ./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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接