[英]Convert String to float in c++
我想將我從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<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
將所有三種類型的字符串轉換為浮點數的最佳方法是什么?
具有正確語言環境集的scanf
。 說真的 在這種情況下,可以省去用“ c ++方式”進行操作的麻煩。
http://www.cplusplus.com/reference/clibrary/clocale/
注意,語言環境配置會影響標准C庫中許多函數的行為:在string.h中,函數strcoll和strxfrm受字符轉換規則的影響。 在ctype.h中,除isdigit和isxdigit外的所有功能均受所選擴展字符集的影響。 在stdio.h中,格式化的輸入/輸出操作受數字格式設置中的字符轉換規則和小數點字符集影響。 在time.h中,函數strftime受時間格式設置的影響。 在此標頭中,它影響其函數setlocale和localeconv返回的值。
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/zh-cn/library/hzz3tw78.aspx
(等等,MSVC setlocale
真的不接受“ en_US”嗎?)
GCC接受以下語言環境: http : //gcc.gnu.org/onlinedocs/libstdc++/manual/localization.html#locale.impl.c
應該這樣做:
#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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.