0

私はこのコードを持っています:

if(flag == 0)
{
// converting string value to integer

istringstream(temp) >> value ;
value = (int) value ; // value is a 
}

istringstream演算子 rightを使用しているかどうかわかりません。変数「値」を整数に変換したい。

Compiler error : Invalid use of istringstream.

どうすれば直せますか?

最初に与えられた答えで修正しようとした後。次のエラーが表示されます:

stoi was not declared in this scope

それを乗り越える方法はありますか。私が現在使用しているコードは次のとおりです。

int i = 0 ;
while(temp[i] != '\0')
{
  if(temp[i] == '.')
     {
       flag = 1;
       double value = stod(temp);
     }
     i++ ;
}
if(flag == 0)
{
// converting string value to integer
int value = stoi(temp) ;
}
4

2 に答える 2

3

本当に別のことをする必要がない限り、次のようなものを使用することを検討してください:

 int value = std::stoi(temp);

を使用する必要がある場合はstringstream、通常、lexical_cast関数でラップして使用します。

 int value = lexical_cast<int>(temp);

そのためのコードは次のようになります。

 template <class T, class U>
 T lexical_cast(U const &input) { 
     std::istringstream buffer(input);
     T result;
     buffer >> result;
     return result;
 }

stoi持っていない場合の模倣方法についてstrtolは、出発点として使用します。

int stoi(const string &s, size_t *end = NULL, int base = 10) { 
     return static_cast<int>(strtol(s.c_str(), end, base);
}

stoiこれは、正しくの要件を実際にはまったく満たしていない、手早く汚い模倣であることに注意してください。たとえば、入力をまったく変換できなかった場合 (たとえば、基数 10 で文字を渡す場合) は、実際には例外をスローする必要があります。

double の場合stod、ほぼ同じ方法で実装できますが、strtod代わりに使用します。

于 2013-04-02T17:59:21.987 に答える
0

まずistringstream、オペレーターではありません。文字列を操作する入力ストリーム クラスです。

次のようなことを行うことができます。

   istringstream temp(value); 
   temp>> value;
   cout << "value = " << value;

ここで istringstream の使用法の簡単な例を見つけることができます: http://www.cplusplus.com/reference/sstream/istringstream/istringstream/

于 2013-04-02T17:59:12.010 に答える