istringstream无效的错误初学者 [英] istringstream invalid error beginner
问题描述
我有这段代码:
if(flag == 0)
{
// converting string value to integer
istringstream(temp) >> value ;
value = (int) value ; // value is a
}
我不知道是否使用 istringstream
操作符权限。我想将变量value转换为整数。
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.
如何解决?
尝试修复第一个给定的答案后。它显示以下错误:
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) ;
}
推荐答案
除非你真的需要否则,考虑只使用类似:
Unless you really need to do otherwise, consider just using something like:
int value = std::stoi(temp);
如果必须使用 stringstream
通常希望使用它包装在 lexical_cast
函数中:
If you must use a stringstream
, you typically want to use it wrapped in a lexical_cast
function:
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
作为起点:
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);
}
注意这是一个快速和脏的模仿, t真正满足 stoi
的要求。例如,如果输入不能被转换,它应该会抛出一个异常(例如,
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).
对于double,你可以以相同的方式实现 stod
,但使用 strtod
。
For double you can implement stod
about the same way, but using strtod
instead.
这篇关于istringstream无效的错误初学者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!