【问题标题】:istringstream invalid error beginneristringstream 无效错误初学者
【发布时间】:2013-04-02 17:52:04
【问题描述】:

我有这段代码:

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

【问题讨论】:

    标签: c++ istringstream


    【解决方案1】:

    除非你真的需要这样做,否则考虑使用类似的东西:

     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 为基数传递字母),它应该真的抛出异常。

    对于双精度,您可以以大致相同的方式实现stod,但改用strtod

    【讨论】:

    • 我是std::stoi(你可能会想到std::to_string):)
    • @novice7: 你有#included &lt;string&gt;吗?这就是定义stoi 的地方。如果您包含了正确的标头,但它仍然无法工作,那么您可能有一个较旧的编译器还没有包含 stoi。您可能希望使用strtol 编写一个小型包装器。
    • 是的,我已经包含了字符串标题。我应该如何实施 strol ?也是双倍的,我该怎么办?它说 stoi 没有在范围内定义。这也与头文件有关吗? @JerryCoffin
    • @novice7:我添加了一些关于如何使用strtrol的内容。
    【解决方案2】:

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

    您可以执行以下操作:

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

    您可以在此处找到 istringstream 使用的简单示例:http://www.cplusplus.com/reference/sstream/istringstream/istringstream/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-17
      • 2017-09-20
      • 2011-02-24
      • 1970-01-01
      相关资源
      最近更新 更多