我已经为此苦苦挣扎了太久。
假设我有这个最少的代码:
test.cxx
#include <iostream>
#include <cstdio>
int main (int argc, char *argv[])
{
const char *text = "1.01 foo";
float value = 0;
char other[8];
int code = sscanf(text, "%f %7s", &value, other);
std::cout << code << " | " << text << " | => | " << value << " | " << other << " | " << std::endl;
return 0;
}
$ g++ 测试.cxx; ./a.out
按预期生成此输出:
$ 2 | 1.01 富 | => | 1.01 |富 |
现在我将这 5 行代码嵌入到一个有几千行代码的项目中,并且包含很多...
编译、运行,现在输出为:
$ 2 | 1.01 富 | => | 1 | .01 |
我可以使用什么策略来定位这种不一致的根源?
编辑:
导出 LC_ALL=C(或 LC_NUMERIC=C); ./a.out
似乎解决了我的问题
最佳答案
这可能是由您的测试和目标应用程序中的不同语言环境引起的。我能够在 coliru 上重现它:
通过使用:
setlocale(LC_ALL, "cs_CZ.utf8");
http://coliru.stacked-crooked.com/a/5a8f2ea7ac330d66
你可以在这个SO中找到一些解决方案:
sscanf() and locales. How does one really parse things like "3.14"?
[编辑]
uselocale
的解决方案,但是既然你用 C++ 标记了这个问题,那么为什么不使用 std::stringstream 并为其注入(inject)适当的语言环境(参见上面的 SO 链接)。
http://coliru.stacked-crooked.com/a/dc0fac7d2533d95c
const char *text = "1.01 foo";
float value = 0;
char other[8];
// set for testing, sscanf will assume floating point numbers use comma instead of dots
setlocale(LC_ALL, "cs_CZ.utf8");
// Temporarily use C locale (uses dot in floats) on current thread
locale_t locale = newlocale(LC_NUMERIC_MASK, "C", NULL);
locale_t old_locale = uselocale(locale);
int code = sscanf(text, "%f %7s", &value, other);
std::cout << code << " | " << text << " | => | " << value << " | " << other << " | " << std::endl;
// Go back to original locale
uselocale(old_locale);
freelocale(locale);
关于c++ - 使用 sscanf 定位错误的来源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37216512/