istringstream 不尊重基地?

istringstream not honoring base?

由于使用 atoiatof,我正在尝试修复 Coverity 关于污染值的一些发现。我切换到 istringstream,但它没有为 10 以外的碱基产生预期结果。

如果我切换到 16 进制,输入 0xa 并避开 iss.ignore(2);,那么结果是 0:

$ ./tt.exe 0xa
X: 0

如果我切换到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;
}

你完全想多了。以十六进制表示法读取值很容易。

#include <sstream>
#include <iomanip>
#include <cassert>

int main()
{
   {
      int x = 0;
      std::istringstream is("0xa");
      is >> std::hex >> x;
      assert(x == 10);
   }
   {
      int x = 0;
      std::istringstream is("a");
      is >> std::hex >> x;
      assert(x == 10);
   }
}

(live demo)


无论如何,我可以确定您的代码有两个问题。

1。 std::ios_base::setf

的错误使用

您正在用 std::ios_base::hex 替换流的整个标志集。这些标志不仅适用于数字基数。为此,您需要屏蔽其他所有内容,以防止取消设置其他不相关但必要的标志(我不知道它们是什么):

iss.setf(std::ios_base::hex, std::ios::basefield);

这就是 iss >> std::hex 如此简单的原因。

这也是为什么你应该构建一个最小的测试用例,其中只包含 只有 iss.setf 的测试才能发布!

2。逻辑错误

输入只是 "a" 的情况会完全跳过该语句,因为它以前两个字符为“0x”为条件。

把它移到 iss >> value 之前,我愿意。


你可以看到你的固定代码 here 但是,正如我在回答开始时所探索的那样,整个 switching-on-leading-"0x" 的事情是不必要的,所以你的大部分代码都可以刚刚被删除。