istringstream invalid error beginner

为君一笑 提交于 2019-12-08 12:13:19

问题


I have this piece of code :

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

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

I am not sure if I am using the istringstream operator right . I want to convert the variable "value" to integer.

Compiler error : Invalid use of istringstream.

How should I fix it ?

After trying to fix with the first given answer . it's showing me the following error :

stoi was not declared in this scope

Is there a way we can work past it . The code i am using right now is :

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

回答1:


Unless you really need to do otherwise, consider just using something like:

 int value = std::stoi(temp);

If you must use a stringstream, you typically want to use it wrapped in a lexical_cast function:

 int value = lexical_cast<int>(temp);

The code for that looks something like:

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

As to how to imitation stoi if your don't have one, I'd use strtol as the starting point:

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

Note that this is pretty much a quick and dirty imitation that doesn't really fulfill the requirements of stoi correctly at all. For example, it should really throw an exception if the input couldn't be converted at all (e.g., passing letters in base 10).

For double you can implement stod about the same way, but using strtod instead.




回答2:


First of all, istringstream is not an operator. It is an input stream class to operate on strings.

You may do something like the following:

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

You can find a simple example of istringstream usage here: http://www.cplusplus.com/reference/sstream/istringstream/istringstream/



来源:https://stackoverflow.com/questions/15770851/istringstream-invalid-error-beginner

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!