【发布时间】:2015-11-14 12:19:34
【问题描述】:
由于使用了atoi 和atof,我正在尝试修复一些关于受污染值的 Coverity 调查结果。我切换到istringstream,但它不会为 10 以外的碱基产生预期结果。
如果我切换到base 16,输入0xa并避开iss.ignore(2);,那么结果是0:
$ ./tt.exe 0xa
X: 0
如果我切换到base 16,输入0xa并使用iss.ignore(2);,那么结果是一个异常:
$ ./tt.exe 0xa
'0xa' is not a value
我按照@πάντα 的推荐访问了CPP Reference on istringstream,但它没有讨论这种情况下的限制。
任何想法我做错了什么?或者,我怎样才能让它按预期工作?
$ cat tt.cxx
#include <iostream>
#include <sstream>
#include <iomanip>
#include <stdexcept>
using namespace std;
template <class T>
T StringToValue(const std::string& str) {
std::istringstream iss(str);
T value;
if (str.length() >= 2) {
if (str[0] == '0' && (str[1] =='X' || str[1] =='x'))
{
iss.setf(std::ios_base::hex);
iss.ignore(2);
}
}
iss >> value;
if (iss.fail())
throw runtime_error("'" + str +"' is not a value");
return value;
}
int main(int argc, char* argv[])
{
try
{
int x = StringToValue<int>(argc >= 2 ? argv[1] : "ZZZ...");
cout << "X: " << x << endl;
}
catch(const runtime_error& ex)
{
cerr << ex.what() << endl;
return 1;
}
return 0;
}
【问题讨论】:
-
读入数字时去掉
0x前缀。 -
啊,我明白了,你已经把
ignore(2)放在那里了。 -
通常的方式是
iss >> hex >> value;。 -
你能做一个minimal测试用例吗?
-
@user1034749 - 我们支持古老的编译器。事实上,我刚刚用 GCC 3.2 在 Fedora 1 上完成了测试。 (我们不像浏览器和苹果操作系统)。