[英]Locate the source of a bug with sscanf
我已經為此苦苦掙扎太久了。
假設我有這個最小的代碼:
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++ test.cxx; ./a.out
$ g++ test.cxx; ./a.out
產生如下輸出:
$ 2 | 1.01 foo | => | 1.01 | foo |
現在,我將這5條線嵌入到具有數千條線的項目中,其中包括很多...
編譯,運行,輸出現在是:
$ 2 | 1.01 foo | => | 1 | .01 |
我可以使用什么策略來找出這種不一致的根源?
編輯: export LC_ALL=C (or LC_NUMERIC=C); ./a.out
export LC_ALL=C (or LC_NUMERIC=C); ./a.out
似乎解決了我的問題
這可能是由測試和目標應用程序中不同的語言環境引起的。 我能夠在coliru上復制它:
通過使用:
setlocale(LC_ALL, "cs_CZ.utf8");
http://coliru.stacked-crooked.com/a/5a8f2ea7ac330d66
您可以在此SO中找到一些解決方案:
sscanf()和語言環境。 如何真正解析“ 3.14”之類的內容?
[編輯]
使用uselocale
解決方案,但是由於您使用C ++標記了這個問題,那么為什么不使用std :: stringstream並使用適當的語言環境來注入它(請參見上面的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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.