c++ - 设置区域设置后输入 4 位数字时,operator>> 返回失败

标签 c++ macos locale c++14

当我使用 imbue 设置时,我遇到了一些非常奇怪的行为 cin 的语言环境。

// example.cpp
#include <iostream>
#include <iomanip>
#include <locale>
int main(){
# ifdef LOCALE
  std::cin.imbue(std::locale(LOCALE));
# endif
  long temp;
  const bool status = static_cast<bool>(std::cin >> temp);
  std::cout << std::boolalpha << status << " " << temp << std::endl;
}

如果我不注入(inject)当前的代码,我可以毫无问题地编译和运行此代码 语言环境。

$ g++ example.cpp -o no-imbue -std=c++1y -stdlib=libc++ -Wall -Wextra -Werror
$ echo 100 | no-imbue
true 100
$ echo 1001 | no-imbue
true 1001

但是,如果我注入(inject)当前区域设置,std::cin >> temp 开始失败 四位数:

$ g++ example.cpp -o imbue-empty -DLOCALE='""' -std=c++1y -stdlib=libc++ -Wall -Wextra -Werror
$ echo 100 | imbue-empty
true 100
$ echo 1001 | imbue-empty
false 1001

使用 "en_US.UTF-8" 作为语言环境名称而不是 "" 似乎具有相同的效果 效果。

$ g++ example.cpp -o imbue-utf8 -DLOCALE='"en_US.UTF-8"' -std=c++1y -stdlib=libc++ -Wall -Wextra -Werror
$ echo 100 | imbue-utf8
true 100
$ echo 1001 | imbue-utf8
false 1001

我在 OSX 上使用 clang-600.0.57

$ g++ --version
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 6.0 (clang-600.0.57) (based on LLVM 3.5svn)
Target: x86_64-apple-darwin13.4.0
Thread model: posix

这是编译器的错误,还是我做错了什么?

最佳答案

如果您输入1,001 ,你的程序应该打印 true .

en_US locale 要求每组三位数之间有一个逗号。因为您没有提供, std::num_get::get() failbitstd::cin 。有关更多详细信息,请参阅链接,但相关摘录是:

Stage 2: character extraction

If the character matches the thousands separator (std::use_facet<std::numpunct<charT>>(str.getloc()).thousands_sep()) and the thousands separation is in use at all std::use_facet<std::numpunct<charT>>(str.getloc()).grouping().length() != 0, then if the decimal point '.' has not yet been accumulated, the position of the character is remembered, but the character is otherwise ignored. If the decimal point has already been accumulated, the character is discarded and Stage 2 terminates.

还有

Stage 3: conversion and storage

After this, digit grouping is checked. if the position of any of the thousands separators discarded in Stage 2 does not match the grouping provided by std::use_facet<std::numpunct<charT>>(str.getloc()).grouping(), std::ios_base::failbit is assigned to err.

关于c++ - 设置区域设置后输入 4 位数字时,operator>> 返回失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38834713/

相关文章:

C++继承循环依赖

C++使函数调用依赖于模板参数

c++ - 在 C++ 程序之间发送数据的基本命名管道?

c++ - C++如何链接模板实例

cocoa - Cocoa 中内置密码验证对话框?

xcode - 在 Swift 中操作 NSDates

objective-c - 向 View 添加许多工具提示时出现问题

android - 设备重启后如何保持应用语言设置?

javascript - 有没有办法使用 javascript 更改浏览时的区域设置?

c# - 使用 .NET 从语言环境字符串中获取语言名称?例如 : en_us => english