使用字符串流浮动的字符串 [英] String to float using stringstream

查看:45
本文介绍了使用字符串流浮动的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在网上找到这段代码作为模板,用于将字符串转换为浮点/整数/双精度.它只是在这里,所以我有一些可以参考的问题......

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

我想让用户输入一个数字作为字符串,将其转换为浮点数,测试它是否成功,如果输入是Q"则退出,如果不是Q"则打印无效输入"uit 字符并返回以获取更多输入.

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.

转换失败测试的语法是什么?会是 ss.fail() 吗?

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
}

没有必要使用失败.

这篇关于使用字符串流浮动的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆