9

有没有办法调整 std::stod() 以增加(字符串到双精度)转换中的小数位数并强制它使用美国语言环境?

我有一个可以在控制台或 gui 模式下运行的 Qt 应用程序:

if (opt->getFlag( 'c' ) || opt->getFlag( "console" ) ){
  ThreadManager  modelMainThread;
  modelMainThread.runFromConsole(inputFileName,scenarioName);
}
else {
  QApplication app(argc, argv);
  MainWindow mainWin;
  mainWin.show();
  return app.exec();
}

在这个应用程序中,我有一个包含新 C++11 stod 的 string to double 方法:

double s2d ( const string &string_h) const {
  try {
    return stod(string_h);
  } catch (...) {
    if (string_h == "") return 0;
    else {
      cout << "error!" << endl;
    }
  }
  return 0;
}

奇怪的是,在控制台模式下,字符串到双重转换需要一个带点作为小数分隔符的字符串,而在 gui 模式下,它需要一个带逗号的字符串。此外,正如我之前使用 istringstream 的那样:

istringstream totalSString( valueAsString );
totalSString >> valueAsDouble;

我注意到 stod 将生成的 double 截断为仅 3 个十进制数字,比 istringstream 少得多。

那么有没有办法增加小数位数并强制 std::stod 使用美国语言环境进行转换?

谢谢 :-)

编辑

如果我尝试这个脚本:

// testing stod() ..
vector<string> numbers;
numbers.push_back("123.1234567890");
numbers.push_back("123.1234");
numbers.push_back("123,1234567890");
numbers.push_back("123,1234");
double outd;
for(uint i=0;i<numbers.size();i++){
    try {
        outd =  stod(numbers[i]);
        cout << "Conversion passed: " << numbers[i] << "  -  " << outd << endl;
    } catch (...) {
        cout << "Conversion DID NOT passed: " << numbers[i] << "  -  " <<endl;
    }
}

我得到了这些结果:

“控制台”模式:

Conversion passed: 123.1234567890  -  123.123
Conversion passed: 123.1234  -  123.123
Conversion passed: 123,1234567890  -  123
Conversion passed: 123,1234  -  123

“gui”模式:

Conversion passed: 123.1234567890  -  123
Conversion passed: 123.1234  -  123
Conversion passed: 123,1234567890  -  123.123
Conversion passed: 123,1234  -  123.123

很明显,有些东西会影响 stod() 的行为!

4

4 回答 4

9

std::stod是根据 定义的std::strtod,它继承自 C 标准库。C 函数strtod根据 C 语言环境工作,可通过标头中的setlocale函数访问<locale.h>

在 C++ 中,C 语言环境仍然可以通过标头std::setlocale中的函数访问<clocale>,并且它确实影响std::strtodstd::stod

QtQApplication用于std::setlocale设置用户选择的语言环境。因此,每当您在 GUI Qt 应用程序中使用依赖于 C 语言环境的函数时,您将拥有依赖于语言环境的小数点。

现在,要强制数字使用特定的语言环境,您可以使用std::setlocale如下。但请注意,这可能会破坏多线程应用程序,因为 C 语言环境是线程全局状态。下面的例子将程序的 locale 临时设置为LC_NUMERIC=C,调用后恢复设置std::stod

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

void test()
{
    for(auto s : {"123.1234567890",
                  "123.1234",
                  "123,1234567890",
                  "123,1234"})
    {
        // Save locale setting
        const std::string oldLocale=std::setlocale(LC_NUMERIC,nullptr);
        // Force '.' as the radix point. If you comment this out,
        // you'll get output similar to the OP's GUI mode sample
        std::setlocale(LC_NUMERIC,"C");
        try
        {
            const auto outd=std::stod(s);
            std::cout << "Conversion succeeded: " << s << "  =>  "
                      << outd << '\n';
        }
        catch (...)
        {
            std::cout << "Conversion FAILED   : " << s << "  =>  ???\n";
        }
        // Restore locale setting
        std::setlocale(LC_NUMERIC,oldLocale.c_str());

    }
}

#include <QApplication>
int main(int argc, char** argv)
{
    std::cout << "Test in normal console mode\n";
    test();
    QApplication app(argc, argv);
    std::cout << "Test in GUI mode\n";
    test();
}

输出:

Test in normal console mode
Conversion succeeded: 123.1234567890  =>  123.123
Conversion succeeded: 123.1234  =>  123.123
Conversion succeeded: 123,1234567890  =>  123
Conversion succeeded: 123,1234  =>  123
Test in GUI mode
Conversion succeeded: 123.1234567890  =>  123.123
Conversion succeeded: 123.1234  =>  123.123
Conversion succeeded: 123,1234567890  =>  123
Conversion succeeded: 123,1234  =>  123
于 2019-01-11T10:50:59.083 回答
5

std::stod及其亲属旨在提供从字符串到数字类型的简单、快速的转换。(完全披露:这是我的设计)所以,不,没有语言环境;你所看到的就是你得到的。

于 2012-09-07T12:00:47.807 回答
3

std::stodstd::string是一种将 a 转换为 double的通用方式。如果你想要更具体的东西,你应该自己实现它。

例如:

double my_stod(const std::string &valueAsString) {
    istringstream totalSString( valueAsString );
    double valueAsDouble;
    // maybe use some manipulators
    totalSString >> valueAsDouble;
    if(!totalSString)
        throw std::runtime_error("Error converting to double");    
    return valueAsDouble;
}
于 2012-09-07T11:26:05.790 回答
0

为了避免在设置语言环境和使用时出现线程问题strtod,我会使用istringstream

#include <optional>
#include <sstream>

[[nodiscard]] std::optional<double>
toDouble( const std::string& stringToConvert)
{
    std::istringstream streamToConvert( stringToConvert );
    streamToConvert.imbue( std::locale( "C" ) );
    double result = 0.0;
    streamToConvert >> result;

    if ( streamToConvert.fail() || streamToConvert.bad() || !streamToConvert.eof() ) {
        return std::nullopt;
    }
    return result;
}

如果你真的不想使用istringstream,你可以尝试调用std::num_get,这是istringstream内部调用的。

于 2021-10-11T13:44:50.793 回答