7

このコードは、文字列を float/int/double に変換するためのテンプレートとしてオンラインで見つけました。ここだけなので質問の参考にさせていただきます…。

ユーザーに数値を文字列として入力させ、それをフロートに変換し、成功するかどうかをテストし、エントリが「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;
}
4

3 に答える 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
}

失敗する必要はありません。

于 2012-10-18T06:46:45.643 に答える
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
    }
}

明らかに、ほとんどの場合、例外をすぐにキャッチしてコールチェーンをバブルアップさせないため、コストが大幅に削減されます。

于 2012-10-18T09:26:45.880 に答える
0

元の質問で要求された機能の一部は次のとおりです。

  1. 入力浮動小数点数の 2 倍の値を出力します
  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
于 2012-11-25T16:24:13.640 に答える