c++ - operator>> returns failure when I enter a 4-digit number after setting the locale -


i'm running weird behaviour when use imbue set locale 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; } 

i can compile , run code without issue if don't imbue current locale.

$ 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 

however, if imbue current locale, std::cin >> temp starts failing 4 digit numbers:

$ 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 

using "en_us.utf-8" locale name instead of "" seems have same effect.

$ 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 

i'm on osx using 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 

is bug compiler, or doing wrong?

if input 1,001, program should print true.

the en_us locale expects comma between each group of 3 digits. because didn't provide one, std::num_get::get() sets failbit on std::cin. see link more detail, relevant excerpts are:

stage 2: character extraction

if character matches thousands separator (std::use_facet<std::numpunct<chart>>(str.getloc()).thousands_sep()) , thousands separation in use @ std::use_facet<std::numpunct<chart>>(str.getloc()).grouping().length() != 0, if decimal point '.' has not yet been accumulated, position of character remembered, character otherwise ignored. if decimal point has been accumulated, character discarded , stage 2 terminates.

and

stage 3: conversion , storage

after this, digit grouping checked. if position of of thousands separators discarded in stage 2 not match grouping provided std::use_facet<std::numpunct<chart>>(str.getloc()).grouping(), std::ios_base::failbit assigned err.


Comments