在 c++ 中将字符串转换为浮点数

发布于 2024-12-08 00:50:23 字数 685 浏览 1 评论 0原文

我想将从 csv 文件读取的 std::string 转换为 float。其中包含几种浮点表示形式,例如:

0,0728239
6.543.584.399
2,67E-02

这些字符串都应该是浮点。首先我使用了atof(),但是转换错误:

2,67E-02 -> 2
6.543.584.399 -> 6.543

然后我使用了boost::lexical_cast(),但是当涉及到带有指数的浮点数时包括在内,它会引发以下异常

`terminate` called after throwing an instance of
`'boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::bad_lexical_cast> >'`
`what()`:  bad lexical cast: source type value could not be interpreted as target
Aborted

将所有三种类型的字符串转换为浮点数的最佳方法是什么?

I want to convert a std::string which I read from a csv file to a float. There are several float representations included like:

0,0728239
6.543.584.399
2,67E-02

These string should all be floats. First I used atof(), but the conversion was wrong:

2,67E-02 -> 2
6.543.584.399 -> 6.543

Then I used boost::lexical_cast<float>(), but when it comes to a float with an exponent included, it throws following exception

`terminate` called after throwing an instance of
`'boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::bad_lexical_cast> >'`
`what()`:  bad lexical cast: source type value could not be interpreted as target
Aborted

What is the best way to get all three types of strings converted to a float?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

执笔绘流年 2024-12-15 00:50:24

scanf 设置了正确的区域设置。严重地。在这种情况下,可以省去用“c++ 方式”进行操作的麻烦。

scanf with the correct locale set. Seriously. Save yourself the hassle of doing it the "c++ way" in this case.

来世叙缘 2024-12-15 00:50:24

http://www.cplusplus.com/reference/clibrary/clocale/

请注意,区域设置配置会影响许多人的行为
标准 C 库中的函数:在 string.h 中,
函数 strcoll 和 strxfrm 受字符转换的影响
规则。在 ctype.h 中,除了 isdigit 和之外的所有函数
isxdigit 受所选扩展字符集的影响。在
stdio.h,格式化输入/输出操作受到影响
通过字符转换规则和小数点字符集
数字格式设置。在 time.h 中,函数
strftime 受时间格式设置的影响。在这个标题中,
它影响其函数 setlocale 和返回的值
语言环境转换。

http://www.cplusplus.com/reference/clibrary/clocale/setlocale/

setlocale ( LC_NUMERIC, "" ); // "" is the Environment's default locale

然后就可以正确使用atof、scanf等了。然而,这就是 C 的做事方式。 C++ 方式是:

float stof(const std::string& input) {
    std::stringstream ss;
    float result;
    static std::locale uselocale("") //again, "" is Environment's default locale
    ss.imbue(uselocale);
    ss << input;
    ss >> result;
    return result;
}

所有编译器都必须接受这些语言环境:“”、“C”
MSVC 接受以下区域设置: http://msdn.microsoft.com/en-us/库/hzz3tw78.aspx
(等等,MSVC setlocale 真的不接受“en_US”吗?)
GCC 接受以下语言环境:http://gcc.gnu。 org/onlinedocs/libstdc++/manual/localization.html#locale.impl.c

http://www.cplusplus.com/reference/clibrary/clocale/

Notice that locale configuration affects the behavior of many
functions within the standard C library: In string.h,
functions strcoll and strxfrm are affected by character transformation
rules. In ctype.h, all functions except for isdigit and
isxdigit are affected by the extended character set selected. In
stdio.h, formatted input/output operations are affected
by character transformation rules and decimal-point character set in
the numeric formatting settings. In time.h, the function
strftime is affected by the time formatting settings. In this header,
it affects the value returned by its functions setlocale and
localeconv.

http://www.cplusplus.com/reference/clibrary/clocale/setlocale/

setlocale ( LC_NUMERIC, "" ); // "" is the Environment's default locale

Then you can use atof, scanf, etc correctly. However, that's the C way of doing things. The C++ way is:

float stof(const std::string& input) {
    std::stringstream ss;
    float result;
    static std::locale uselocale("") //again, "" is Environment's default locale
    ss.imbue(uselocale);
    ss << input;
    ss >> result;
    return result;
}

All compilers must accept these locales: "", "C"
MSVC accepts these locales: http://msdn.microsoft.com/en-us/library/hzz3tw78.aspx
(wait, does MSVC setlocale really not accept "en_US"?)
GCC accepts these locales: http://gcc.gnu.org/onlinedocs/libstdc++/manual/localization.html#locale.impl.c

白芷 2024-12-15 00:50:24

应该这样做:

#include <sstream>
#include <iostream>
#include <algorithm>

bool isdot(const char &c)
{
    return '.'==c;
}

float to(std::string s)
{
    s.erase(std::remove_if(s.begin(), s.end(), &isdot ),s.end());
    replace(s.begin(), s.end(), ',', '.');


    std::stringstream ss(s);
    float v = 0;
    ss >> v;
    return v;
}

int main()
{
    const std::string a1("0,0728239");
    const std::string a2("6.543.584.399");
    const std::string a3("2,67E-02");

    std::cout << to(a1)<<std::endl;
    std::cout << to(a2)<<std::endl;
    std::cout << to(a3)<<std::endl;
}

在 coliru 上实时查看

This should do :

#include <sstream>
#include <iostream>
#include <algorithm>

bool isdot(const char &c)
{
    return '.'==c;
}

float to(std::string s)
{
    s.erase(std::remove_if(s.begin(), s.end(), &isdot ),s.end());
    replace(s.begin(), s.end(), ',', '.');


    std::stringstream ss(s);
    float v = 0;
    ss >> v;
    return v;
}

int main()
{
    const std::string a1("0,0728239");
    const std::string a2("6.543.584.399");
    const std::string a3("2,67E-02");

    std::cout << to(a1)<<std::endl;
    std::cout << to(a2)<<std::endl;
    std::cout << to(a3)<<std::endl;
}

See it live on coliru

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文