c++ - 使用 sscanf 定位错误的来源

标签 c++ cstdio

我已经为此苦苦挣扎了太久。

假设我有这个最少的代码:

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/

相关文章:

c++ - 您可以将引用绑定(bind)到未初始化的成员吗?

c++ - 从 C++ 调用 powershell cmdlet

c++ - 如何重载不接受或不返回 ostream 的运算符 <<

C++:如何为控制台应用程序设置新的 wndProc?

c++ - 为什么 sscanf 无法从一个字符串中读取 uint64_t 和 char?

C++:fopen() 返回空文件句柄

c++ - 我如何在 Red Hat 上强制使用 cxx11 ABI?

c++ - 我无法理解为什么在此 for 循环中输出为 10

c - 如何在C中中断覆盖文件时避免丢失数据

c - 使用 fscanf() 时不理解 C 格式说明符