草庐IT

c++ - stod 不能与 boost::locale 一起正常工作

coder 2024-02-20 原文

我试图在逗号是小数分隔符的德国语言环境中一起使用 boost::locale 和 std::stod 。考虑这个代码:

boost::locale::generator gen;

std::locale loc("");  // (1)
//std::locale  loc = gen("");  // (2)

std::locale::global(loc);
std::cout.imbue(loc);

std::string s = "1,1";  //float string in german locale!
double d1 = std::stod(s);
std::cout << "d1: " << d1 << std::endl;

double d2 = 2.2;
std::cout << "d2: " << d2 << std::endl;

std::locale loc("") 创建正确的语言环境,输出为
d1: 1,1
d2: 2,2

正如我所料。当我注释掉第 (1) 行和取消注释第 (2) 行时,输出是
d1: 1
d2: 2.2

d2 的结果在意料之中。据我了解 boost::locale 希望我明确指定 d2 应该被格式化为一个数字并做
std::cout << "d2: " << boost::locale::as::number << d2 << std::endl;

再次将输出固定为 2,2。问题是 std::stod 不再将 1,1 视为有效的浮点数并将其截断为 1。

我的问题是:
为什么当我使用 boost::locale 生成语言环境时 std::stod 停止工作?

附加信息:我使用的是 VC++2015,Boost 1.60,没有 ICU,Windows 10

更新:

我注意到当我设置全局语言环境两次时问题得到解决,首先使用 std::locale("") 然后使用 boost:
std::locale::global(std::locale(""));
bl::generator gen;
std::locale::global(gen(""));

不过,我不知道它为什么会这样!

最佳答案

长话短说: boost::locale仅更改全局 c++-locale 对象,而不更改 C-locale。 stod使用 C-locale 而不是全局 c++-locale 对象。 std::locale两者都改变​​:全局 c++-locale 对象和 C 语言环境。

整个故事: std::locale是一件微妙的事情,负责大量的调试!

让我们从 C++ 类 std::locale 开始:

  std::locale loc("de_DE.utf8");  
  std::cout<<loc.name()<<"\n\n\n";

创建德语语言环境(如果它在您的机器上可用,否则会抛出),结果是 de_DE.utf8在控制台上。

但是它不会改变 全局 c++ 语言环境对象,它在程序启动时创建并且是经典的(“C”)。 std::locale的构造函数不带参数返回全局状态的拷贝:
...
  std::locale loc2;
  std::cout<<loc2.name()<<"\n\n\n";

现在你应该看到 C如果之前没有搞乱你的语言环境。 std::locale("") 会做一些魔术并找出用户的偏好并将其作为对象返回,没有 改变全局状态。

您可以使用 std::local::global 更改本地状态:
  std::locale::global(loc);
  std::locale loc3;
  std::cout<<loc3.name()<<"\n\n\n";

这次默认构造函数的结果是 de_DE.utf8在控制台上。
我们可以通过调用将全局状态恢复到经典状态:
  std::locale::global(std::locale::classic());
  std::locale loc4;
  std::cout<<loc4.name()<<"\n\n\n";

这应该给你 C再次。

现在,当创建 std::cout 时,它会从全局 c++ 状态中克隆其语言环境(这里我们使用 stringstreams 进行操作,但它是相同的)。全局状态的后续更改不会影响流:
 //classical formating
  std::stringstream c_stream;

 //german formating:
  std::locale::global(std::locale("de_DE.utf8"));
  std::stringstream de_stream;

  //same global locale, different results:
  c_stream<<1.1;
  de_stream<<1.1;

  std::cout<<c_stream.str()<<" vs. "<<de_stream.str()<<"\n";

给你1.1 vs. 1,1 - 第一个是古典第二个德国

您可以使用 imbue(std::locale::classic()) 更改流的本地语言环境对象。不用说,这不会改变全局状态:
  de_stream.imbue(std::locale::classic());
  de_stream<<" vs. "<<1.1;
  std::cout<<de_stream.str()<<"\n";
  std::cout<<"global c++ state: "<<std::locale().name()<<"\n";

你会看到:
1,1 vs. 1.1
global c++ state: de_DE.utf8

现在我们来到std::stod .正如您所想象的那样,它使用全局 C++ 语言环境(不完全正确,请耐心等待)状态而不是 cout 的(私有(private))状态。 -溪流:
std::cout<<std::stod("1.1")<<" vs. "<<std::stod("1,1")<<"\n";

给你1 vs. 1.1因为全局状态仍然是 "de_DE.utf8" ,所以第一次解析在 '.' 处停止但是std::cout的本地状态还在"C" .恢复全局状态后,我们得到经典行为:
  std::locale::global(std::locale::classic());
  std::cout<<std::stod("1.1")<<" vs. "<<std::stod("1,1")<<"\n";

现在德国"1,1"未正确解析:1.1 vs. 1
现在你可能认为我们已经完成了,但还有更多 - 我答应告诉你 std::stod .

在全局 c++ 语言环境旁边有所谓的(全局)C 语言环境(来自 C 语言,不要与经典的“C”语言环境混淆)。每次我们更改全局 C++ 语言环境时,C 语言环境也已更改。

可以使用 std::setlocale(...) 来获取/设置 C 语言环境。 .要查询当前值运行:
std::cout<<"(global) C locale is "<<std::setlocale(LC_ALL,NULL)<<"\n";

(global) C locale is C . 要设置 C 语言环境,请运行:
  assert(std::setlocale(LC_ALL,"de_DE.utf8")!=NULL);
  std::cout<<"(global) C locale is "<<std::setlocale(LC_ALL,NULL)<<"\n";

产生 (global) C locale is de_DE.utf8 .但是现在全局 c++ 语言环境是什么?
std::cout<<"global c++ state: "<<std::locale().name()<<"\n";

正如您所料,C 对 C++ 全局语言环境一无所知,并且保持不变:global c++ state: C .

现在我们不在堪萨斯了!旧的 c 函数将使用 C 语言环境,而新的 c++ 函数将使用全局 c++。为有趣的调试做好准备!

你会期待什么
std::cout<<"C: "<<std::stod("1.1")<<" vs. DE :"<<std::stod("1,1")<<"\n";

去做? std::stod毕竟是一个全新的c++11函数,它应该使用全局c++语言环境!再想一想...:
1 vs. 1.1

它获得了正确的德语格式,因为 C 语言环境设置为“de_DE.utf8”并且它在幕后使用旧的 C 样式函数。

只是为了完整起见,std::streams使用全局 c++ 语言环境:
  std::stringstream stream;//creating with global c++ locale
  stream<<1.1;
  std::cout<<"I'm still in 'C' format: "<<stream.str()<<"\n";

给你:I'm still in 'C' format: 1.1 .

编辑:一种解析字符串的替代方法,不会弄乱全局语言环境或被它打扰:
bool s2d(const std::string &str, double  &val, const std::locale &loc=std::locale::classic()){

  std::stringstream ss(str);
  ss.imbue(loc);
  ss>>val;
  return ss.eof() && //all characters interpreted
         !ss.fail(); //nothing went wrong
}

以下测试显示:
  double d=0;
  std::cout<<"1,1 parsed with German locale successfully :"<<s2d("1,1", d, std::locale("de_DE.utf8"))<<"\n";
  std::cout<<"value retrieved: "<<d<<"\n\n";

  d=0;
  std::cout<<"1,1 parsed with Classical locale successfully :"<<s2d("1,1", d, std::locale::classic())<<"\n";
  std::cout<<"value retrieved: "<<d<<"\n\n";

  d=0;
  std::cout<<"1.1 parsed with German locale successfully :"<<s2d("1.1", d, std::locale("de_DE.utf8"))<<"\n";
  std::cout<<"value retrieved: "<<d<<"\n\n";

  d=0;
  std::cout<<"1.1 parsed with Classical locale successfully :"<<s2d("1.1", d, std::locale::classic())<<"\n";
  std::cout<<"value retrieved: "<<d<<"\n\n";

只有第一次和最后一次转换成功:
1,1 parsed with German locale successfully :1
value retrieved: 1.1

1,1 parsed with Classical locale successfully :0
value retrieved: 1

1.1 parsed with German locale successfully :0
value retrieved: 11

1.1 parsed with Classical locale successfully :1
value retrieved: 1.1

std::stringstream 可能不是最快的,但有它的优点......

关于c++ - stod 不能与 boost::locale 一起正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34744911/

有关c++ - stod 不能与 boost::locale 一起正常工作的更多相关文章

  1. ruby-on-rails - 由于 "wkhtmltopdf",PDFKIT 显然无法正常工作 - 2

    我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-

  2. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

  3. ruby-on-rails - 如何优雅地重启 thin + nginx? - 2

    我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server

  4. ruby - 无法让 RSpec 工作—— 'require' : cannot load such file - 2

    我花了三天的时间用头撞墙,试图弄清楚为什么简单的“rake”不能通过我的规范文件。如果您遇到这种情况:任何文件夹路径中都不要有空格!。严重地。事实上,从现在开始,您命名的任何内容都没有空格。这是我的控制台输出:(在/Users/*****/Desktop/LearningRuby/learn_ruby)$rake/Users/*******/Desktop/LearningRuby/learn_ruby/00_hello/hello_spec.rb:116:in`require':cannotloadsuchfile--hello(LoadError) 最佳

  5. ruby-on-rails - rspec should have_select ('cars' , :options => ['volvo' , 'saab' ] 不工作 - 2

    关闭。这个问题需要detailsorclarity.它目前不接受答案。想改进这个问题吗?通过editingthispost添加细节并澄清问题.关闭8年前。Improvethisquestion在首页我有:汽车:VolvoSaabMercedesAudistatic_pages_spec.rb中的测试代码:it"shouldhavetherightselect"dovisithome_pathit{shouldhave_select('cars',:options=>['volvo','saab','mercedes','audi'])}end响应是rspec./spec/request

  6. ruby-on-rails - s3_direct_upload 在生产服务器中不工作 - 2

    在Rails4.0.2中,我使用s3_direct_upload和aws-sdkgems直接为s3存储桶上传文件。在开发环境中它工作正常,但在生产环境中它会抛出如下错误,ActionView::Template::Error(noimplicitconversionofnilintoString)在View中,create_cv_url,:id=>"s3_uploader",:key=>"cv_uploads/{unique_id}/${filename}",:key_starts_with=>"cv_uploads/",:callback_param=>"cv[direct_uplo

  7. ruby-on-rails - 如果我将 ruby​​ 版本 2.5.1 与 rails 版本 2.3.18 一起使用会怎样? - 2

    如果我使用ruby​​版本2.5.1和Rails版本2.3.18会怎样?我有基于rails2.3.18和ruby​​1.9.2p320构建的rails应用程序,我只想升级ruby的版本,而不是rails,这可能吗?我必须面对哪些挑战? 最佳答案 GitHub维护apublicfork它有针对旧Rails版本的分支,有各种变化,它们一直在运行。有一段时间,他们在较新的Ruby版本上运行较旧的Rails版本,而不是最初支持的版本,因此您可能会发现一些关于需要向后移植的有用提示。不过,他们现在已经有几年没有使用2.3了,所以充其量只能让更

  8. ruby-on-rails - 无法让 rspec、spork 和调试器正常运行 - 2

    GivenIamadumbprogrammerandIamusingrspecandIamusingsporkandIwanttodebug...mmm...let'ssaaay,aspecforPhone.那么,我应该把“require'ruby-debug'”行放在哪里,以便在phone_spec.rb的特定点停止处理?(我所要求的只是一个大而粗的箭头,即使是一个有挑战性的程序员也能看到:-3)我已经尝试了很多位置,除非我没有正确测试它们,否则会发生一些奇怪的事情:在spec_helper.rb中的以下位置:require'rubygems'require'spork'

  9. ruby - JetBrains RubyMine 3.2.4 调试器不工作 - 2

    使用Ruby1.9.2运行IDE提示说需要gemruby​​-debug-base19x并提供安装它。但是,在尝试安装它时会显示消息Failedtoinstallgems.Followinggemswerenotinstalled:C:/ProgramFiles(x86)/JetBrains/RubyMine3.2.4/rb/gems/ruby-debug-base19x-0.11.30.pre2.gem:Errorinstallingruby-debug-base19x-0.11.30.pre2.gem:The'linecache19'nativegemrequiresinstall

  10. ruby - 使用 `+=` 和 `send` 方法 - 2

    如何将send与+=一起使用?a=20;a.send"+=",10undefinedmethod`+='for20:Fixnuma=20;a+=10=>30 最佳答案 恐怕你不能。+=不是方法,而是语法糖。参见http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html它说Incommonwithmanyotherlanguages,Rubyhasasyntacticshortcut:a=a+2maybewrittenasa+=2.你能做的最好的事情是:

随机推荐