0

我有这段代码:

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

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

我不确定我是否使用istringstream正确的操作员。我想将变量“值”转换为整数。

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);

如果您必须使用 a 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 为基数传递字母),它应该真的抛出异常。

对于双精度,您可以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 回答