简体   繁体   English

将String转换为C ++中的float

[英]Convert String to float in c++

I want to convert a std::string which I read from a csv file to a float . 我想将我从csv文件读取的std::string转换为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: 首先,我使用了atof() ,但是转换是错误的:

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 然后我使用了boost::lexical_cast<float>() ,但是当涉及到包含指数的浮点数时,它会引发以下异常

`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? 将所有三种类型的字符串转换为浮点数的最佳方法是什么?

scanf with the correct locale set. 具有正确语言环境集的scanf Seriously. 说真的 Save yourself the hassle of doing it the "c++ way" in this case. 在这种情况下,可以省去用“ c ++方式”进行操作的麻烦。

http://www.cplusplus.com/reference/clibrary/clocale/ 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. 注意,语言环境配置会影响标准C库中许多函数的行为:在string.h中,函数strcoll和strxfrm受字符转换规则的影响。 In ctype.h, all functions except for isdigit and isxdigit are affected by the extended character set selected. 在ctype.h中,除isdigit和isxdigit外的所有功能均受所选扩展字符集的影响。 In stdio.h, formatted input/output operations are affected by character transformation rules and decimal-point character set in the numeric formatting settings. 在stdio.h中,格式化的输入/输出操作受数字格式设置中的字符转换规则和小数点字符集影响。 In time.h, the function strftime is affected by the time formatting settings. 在time.h中,函数strftime受时间格式设置的影响。 In this header, it affects the value returned by its functions setlocale and localeconv. 在此标头中,它影响其函数setlocale和localeconv返回的值。

http://www.cplusplus.com/reference/clibrary/clocale/setlocale/ 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. 然后,您可以正确使用atof,scanf等。 However, that's the C way of doing things. 但是,这就是C的处理方式。 The C++ way is: 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;
}

All compilers must accept these locales: "", "C" 所有编译器都必须接受以下语言环境:“”,“ C”
MSVC accepts these locales: http://msdn.microsoft.com/en-us/library/hzz3tw78.aspx MSVC接受以下语言环境: http : //msdn.microsoft.com/zh-cn/library/hzz3tw78.aspx
(wait, does MSVC setlocale really not accept "en_US"?) (等等,MSVC setlocale真的不接受“ en_US”吗?)
GCC accepts these locales: http://gcc.gnu.org/onlinedocs/libstdc++/manual/localization.html#locale.impl.c GCC接受以下语言环境: http : //gcc.gnu.org/onlinedocs/libstdc++/manual/localization.html#locale.impl.c

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 在coliru上实时观看

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM