寫在文章開頭的話
讀完這篇文章後,你將學到下面的知識:
(1)如何利用標準庫中的 std::stringstream 來完成字符串和數值類型的相互轉換
(2)如何利用 C++11 提供的字符串轉換函數,將std::string類型轉換爲數值類型
在C++編程中有時會遇到字符串和數字的相互轉化,以前學習的時候老師喜歡將這種轉化當成作業,要我們寫函數實現。但是實際爲了方便準確還是會優先使用STL來完成。
#include <iostream>
#include <sstream>
int main()
{
string str = "12 3.14";
istringstream in(str);
int v1;
double v2;
in >> v1 >> v2;
cout << "v1=" << v1 << " ,v2=" << v2 << endl;
return 0;
}
#include <iostream>
#include <sstream>
int main()
{
int v1 = 12;
float v2 = 2.14f;
double v3 = 3.1415926;
long long v4 = 0x0123456789ABCDEF;
ostringstream out;
out << v1 << " "
<< v2 << " "
<< v3 << " "
<< hex << uppercase << v4;
cout << "str=" << out.str() << endl;
return 0;
}
由於 stringstream 沒有重載字節類型的轉換,可以通過限制寬度達到轉換字節的目的,例如下面:
unsigned char b = 0xAB;
std::ostringstream out;
out.width(2);
out << std::hex << std::uppercase << static_cast<unsigned short>(b);
#include <string>
#include <iostream>
using namespace std;
int main()
{
string s1 = "1234";
string s2 = "3.14";
int v1 = std::stoi(s1);
float v2 = std::stof(s2);
cout << v1 << " " << v2 << endl;
string s3 = std::to_string(static_cast<long double>(v2)) + "15926";
cout << s3 << endl;
return 0;
}
3.1415926