C++ 字符串與數字之間的轉換


1. 數字轉字符串

方法一

使用C++11標准新增的to_string函數:

string to_string (int val);
string to_string (long val);
string to_string (long long val);
string to_string (unsigned val);
string to_string (unsigned long val);
string to_string (unsigned long long val);
string to_string (float val);
string to_string (double val);
string to_string (long double val);

測試:

int i = 100123;
double d = 100.123;
cout << to_string(i) << endl;
cout << to_string(d) << endl;

輸出:

10123
100.123000

方法二

使用stringstream類:

template<typename out_type, typename in_value>
out_type convert(const in_value & t){
    stringstream stream;
    stream << t;//向流中傳值
    out_type result;//這里存儲轉換結果
    stream >> result;//向result中寫入值
    return result;
}

測試:

int i = 100123;
double d = 100.123;
cout << itos(i) << endl;
cout << dtos(d) << endl;

輸出:

100123
100.123

2. 字符串轉數字

字符串類提供了一系列的轉換函數:

stoi    // Convert string to integer (function template )
stol    // Convert string to long int (function template )
stoul   // Convert string to unsigned integer (function template )
stoll   // Convert string to long long (function template )
stoull  // Convert string to unsigned long long (function template )
stof    // Convert string to float (function template )
stod    // Convert string to double (function template )
stold   // Convert string to long double (function template )

測試:

cout << stoi("123123") << endl;
cout << stod("123.123") << endl;

輸出:

123123
123.123


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM