字串轉換為資料

2021-09-25 13:29:14 字數 2213 閱讀 1031

#include #include //通過字元流資料轉換

templatestatic t str2num(const std::string& string_tmp)

//c++11新標準提供了一系列函式

//c++11標準允許字串裡出現非數字字元--會忽略起始的白空格,直到遇到無法轉換的字元為止。

assert(std::atoi(" 100 ") == 100); //轉換int,執行有空格

static void str2int(int& int_tmp, const string& string_tmp)

assert(std::atof(" 3.1415926") == 3.1415926); //轉換float,執行有空格

static void str2float(float& float_tmp, const string& string_tmp)

assert(std::stol("100l") == 100l); //轉換long, 支援l等字尾

static void str2long(long& long_tmp, const string& string_tmp)

assert(std::stol("1000 9") == 1000l); //轉換long, 後面的被忽略

static void str2long(long& long_tmp, const string& string_tmp)

assert(std::stod("3.14ispi") == 3.14); //轉換double, 遇到無效的字元停止

static void str2double(double& double_tmp, const string& string_tmp)

//boost庫中的lexical_cast,提供了一組模板,不同的模板對應不同的資料型別轉換

//下面列出兩種主要使用的模板型別

template inline target lexical_cast(const source &arg)

return result;

}template inline target lexical_cast(const char* chars, std::size_t count)

//下面是lexical_cast呼叫的基本用法

int x = boost::lexical_cast("100"); //字串->整型 100

long y = boost::lexical_cast("2000"); //字串->長整型 2000

float pai = boost::lexical_cast("3.14159"); //字串->符點型 3.14159

double e = boost::lexical_cast("2.71828"); //字串->雙精度符點型 2.71828

double r = boost::lexical_cast("1.414abcdefg", 5); //c字串->雙精度符點型(只轉前5位) 1.141

std::string ss = boost::lexical_cast(1234567); //數值->字串 1234567

std::string str = boost::lexical_cast(0.618); //雙精度符點型->字串 0.61799999999999999

std::string str2 = boost::lexical_cast(0x10); //16進製制數->字串 16

//注:字串轉數字時,字串中不能包含除數字以外的字元(表示指數的e/e除外)。

//例如,不能將"123l"、"0x100"這樣的字串轉換成數字。

//寫成通用的模板形式

#include #include #include templatestatic bool str2num(const std::string& str, dtype& ddefault = 0)

catch(...) }

//把字串按指定的分隔符轉換為數字

templatestatic bool str2nums(const std::string& ssrc, std:; vector& anums, const std::string ssep = " ")

} catch (const boost::bad_lexical_cast& e)

}return true;

}

字串轉換為整數

class program catch exception ee console.read 轉換類 public class strconverter bool positive true int32 result 0 double tempresult 0 int start 0 while st...

字串轉換為整數

題目 輸入乙個表示整數的字串,把該字串轉換成整數並輸出。例如輸入字串 345 則輸出整數345。分析 這道題儘管不是很難,學過c c 語言一般都能實現基本功能,但不同程式設計師就這道題寫出的 有很大區別,可以說這道題能夠很好地反應出程式設計師的思維和程式設計習慣,因此已經被包括微軟在內的多家公司用作...

字串轉換為整型

在swift中,字串轉換為整型的方法有兩種,我們在這裡比較一下這兩種方法的區別 1 使用強制型別轉換,如下 var str 1234 var integer int str print integer 輸出1234 但如果換乙個字串 var str 123,4 var integer int str...