C++各種格式轉換
阿新 • • 發佈:2020-07-08
int main()
{
stringstream sstr;
//--------int轉string-----------
int a=100;
string str;
sstr<<a;
sstr>>str;
cout<<str<<endl;
//如果你想通過使用同一stringstream物件實現多種型別的轉換,請注意在每一次轉換之後都必須呼叫clear()成員函式。
sstr.clear();
//--------string轉char[]--------
string name = "colinguan";
char cname[200];sstr<<name;
sstr>>cname;
cout<<cname<<endl;
sstr.clear();
//--------string轉double/int--------
double dVal;
int iVal;
stringstream ss;
// string -> double
str = "123.456789";
ss << str;
ss >> dVal;
cout << "dVal: "
<< dVal << endl;
ss.clear();// string -> int
str = "654321";
ss << str;
ss >> iVal;
cout << "iVal: "
<< iVal << endl;
ss.clear();
}