首页 文章

istringstream无效的错误初学者

提问于
浏览
0

我有这段代码:

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

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

我不确定我是否正在使用 istringstream 运算符 . 我想将变量"value"转换为整数 .

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

2 回答

  • 0

    除非你真的需要这样做,否则考虑使用以下内容:

    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 如果你的't have one, I'使用 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 代替 .

  • 3

    首先, istringstream 不是运营商 . 它是一个对字符串进行操作的输入流类 .

    您可以执行以下操作:

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

    你可以在这里找到一个简单的istringstream用法示例:http://www.cplusplus.com/reference/sstream/istringstream/istringstream/

相关问题