C++ 使用sscanf查找错误源
我已经为此挣扎太久了 假设我有一个最小的代码: 测试.cxxC++ 使用sscanf查找错误源,c++,cstdio,C++,Cstdio,我已经为此挣扎太久了 假设我有一个最小的代码: 测试.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);
#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;
}
#包括
#包括
int main(int argc,char*argv[])
{
const char*text=“1.01 foo”;
浮点数=0;
其他[8];
int code=sscanf(文本,“%f%7s”&值,其他);
std::cout这可能是由测试和目标应用程序中的不同区域设置引起的。我能够在coliru上复制它:
通过使用:
setlocale(LC_ALL, "cs_CZ.utf8");
您可以在这方面找到一些解决方案,因此:
[编辑]
<>解决方案,使用<代码> USELOCLA.< /Cord>,但是既然用C++标记了这个问题,那么为什么不使用STD::StrugSnand并用适当的区域设置它(参见上面的链接)。
const char*text=“1.01 foo”;
浮点数=0;
其他[8];
//设置为测试时,sscanf将假定浮点数使用逗号而不是点
setlocale(LC_ALL,“cs_CZ.utf8”);
//在当前线程上临时使用C语言环境(使用浮点中的点)
locale\u t locale=newlocale(LC\u数字掩码,“C”,NULL);
locale\u t old\u locale=uselocale(locale);
int code=sscanf(文本,“%f%7s”&值,其他);
std::cout您使用的是什么平台?可能是Atmel AVR之类的?在某些平台上启用printf
/scanf
中的浮点支持需要在这些函数的特殊版本中进行链接。在Ubuntu 16.04、gcc 5.3.1上使用cmake进行配置,无需交叉编译……还有,可能是区域设置吗在那个大项目中是不同的?例如,在某些地区,
不被认为是小数部分的有效部分(,被用来代替
)哦,我要深入研究一下!谢谢marcinj,我想我不能在运行时改变这种行为,可以吗?Coliru看起来确实很方便,我会记住这一点。。。
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);