【发布时间】:2013-12-03 13:25:06
【问题描述】:
我无法让 Visual-C++ (VS 2005) 中的 printf 函数在我的整数中输出千位分隔符。
注意:评论表明这是printf 的正常行为。但是,C++ iostream 确实 将千位分隔符插入到数字中(使用 std::stringstream 和 imbue 进行了测试),所以这纯粹是 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
【问题讨论】:
-
你确定 printf 应该这样做吗?
-
我从来不知道 %d 在其输出中包含数千个分隔符...
-
@JoeZ - 那么做什么呢?
-
这个问题没有得到满意的答案后你要写的自定义函数:)
-
LC_NUMERIC:确定数字格式的区域设置。此环境变量会影响使用 e、E、f、g 和 G 转换字符写入的数字的格式。
标签: c++ c visual-c++ internationalization locale