【问题标题】:Why debugging and running outputs are different in C++?为什么在 C++ 中调试和运行输出不同?
【发布时间】:2020-09-09 02:05:06
【问题描述】:

我想读取“.text”文件并将字符串转换为双精度。在调试模式下,我可以将文本读取为 99,03,但在运行模式下,我只能读取 99。我不明白会怎样?我的转换代码如下

   double a = std::stod(text)

【问题讨论】:

  • 调试和发布之间可能有不同的区域设置。
  • 也许“运行模式”使用与“调试模式”不同的语言环境。在美国数字语言环境中,99,03 是用逗号分隔的两个整数。在某些欧洲语言环境中,99,03 是十进制值 99.03

标签: c++


【解决方案1】:

std::stod 受语言环境影响。

#include <iostream>
#include <string>
#include <clocale>

int main(void){
    std::setlocale(LC_ALL, "C");

    std::string s{"99.03"}; 
    double d = std::stod( s );
    std::cout<< d << "\n";
    std::setlocale(LC_ALL, "de_DE.UTF-8"); // A locale installed on your machine.
    std::string s2{"99,03"};
    double d2 = std::stod( s2 );
    std::cout<< d2 << "\n";
}

您可能会得到如下结果:(在 msvc 和 gcc 9.3.0 上测试)

99.03
99.03

如果你想std::cout 也打印逗号作为小数分隔符,imbue 是必需的。您可以参考this post

【讨论】:

    猜你喜欢
    • 2012-05-15
    • 2014-09-04
    • 1970-01-01
    • 2019-02-01
    • 2011-11-09
    • 1970-01-01
    • 1970-01-01
    • 2016-05-12
    • 2010-12-29
    相关资源
    最近更新 更多