gpt4 book ai didi

c++ - printf 输出不受全局语言环境影响?

转载 作者:太空宇宙 更新时间:2023-11-04 05:40:29 25 4
gpt4 key购买 nike

我无法让 Visual-C++ (VS 2005) 中的 printf 函数在我的整数中输出千位分隔符。

注意:注释表明这是 printf 的正常行为。但是,C++ iostream 确实将千位分隔符插入到数字中(使用 std::stringstreamimbue 测试)所以这纯粹是 iostreams 的一个功能并且不存在于“C”格式化函数中?

测试代码如下:

    setlocale(LC_ALL, ""); // -> User locale
_locale_t loc = _create_locale(LC_ALL, ""); // -> user locale for *_l version

struct lconv *pLocalSettings = localeconv();
printf("Locale is: %s\n", setlocale(LC_NUMERIC, NULL));
printf("Thousands separator set to : {%s}\n", pLocalSettings->thousands_sep);
printf("Grouping set to: {%o}\n", int(pLocalSettings->grouping[0]));

int i = 1000000;
__int64 i64 = i * 2;
printf("32 Bit integer output: %d\n", i);
printf("64 Bit integer output: %I64d\n", i64);
_printf_l("32 Bit integer output: %d\n", /*locale=*/loc, i);
_printf_l("64 Bit integer output: %I64d\n", /*locale=*/loc, i64);
_free_locale(loc);

输出是:

Locale is: German_Austria.1252
Thousands separator set to : {.}
Grouping set to: {3}
32 Bit integer output: 1000000
64 Bit integer output: 2000000
32 Bit integer output: 1000000
64 Bit integer output: 2000000

进一步检查后,它似乎不是这样工作的。我试过这个:

#include <iostream>
#include <clocale>
using namespace std;

int main() {
setlocale(LC_ALL, "en_US"); // -> User locale

struct lconv *pLocalSettings = localeconv();
printf("Locale is: %s\n", setlocale(LC_NUMERIC, NULL));
printf("Thousands separator set to : {%s}\n", pLocalSettings->thousands_sep);
printf("Grouping set to: {%o}\n", int(pLocalSettings->grouping[0]));

int i = 1000000;
long long i64 = i * 2;
printf("32 Bit integer output: %d\n", i);
printf("64 Bit integer output: %I64d\n", i64);

return 0;
}

关于 http://www.compileonline.com/compile_cpp11_online.php (在那里找不到固定链接。)

输出是:

Compiling the source code....
$g++ -std=c++11 main.cpp -o demo -lm -pthread -lgmpxx -lgmp -lreadline 2>&1

Executing the program....
$demo
Locale is: en_US
Thousands separator set to : {,}
Grouping set to: {3}
32 Bit integer output: 1000000
64 Bit integer output: 2000000

最佳答案

让我分享一下我在这里学到的东西:

  • C 语言环境确实包含有关千位分隔符的信息,但此信息是not used at all printf* 函数系列(除非您将 flag extension ' 计算在内,无论如何它都不存在于 MSVC 中)
  • C++ 语言环境也包含该信息,而 iostreams 在格式化数字 (numpunct facet) 时实际上使用
  • 使用 setlocale 设置全局 C 语言环境不会影响全局 C++ 语言环境设置std::locale::global()

  • 获取格式化数字的正确代码最终是:

    static std::locale user_locale("");
    std::wstringstream buf;
    buf.imbue(user_locale);
    buf << some_integer;
  • 对于某些用例,可以通过 using the facet directly 获得性能提升.

关于c++ - printf 输出不受全局语言环境影响?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20352438/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com