1. 程式人生 > 實用技巧 >C++各種格式轉換

C++各種格式轉換

int main()
{
stringstream sstr;
//--------intstring-----------
int a=100;
string str;
sstr<<a;
sstr>>str;
cout<<str<<endl;
//如果你想通過使用同一stringstream物件實現多種型別的轉換,請注意在每一次轉換之後都必須呼叫clear()成員函式。
sstr.clear();
//--------stringchar[]--------
string name = "colinguan";
char cname[200];

sstr<<name;
sstr>>cname;
cout<<cname<<endl;
sstr.clear();
//--------stringdouble/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();
}