int main() { string pi = "pi is " + to_string(3.1415926); float val = 8.967; string num = to_string(val); string perfect = to_string(1+2+4+7+14) + " is a perfect number";
cout << pi << "\n"; cout << num << "\n"; cout << perfect << "\n"; }
int main() { ostringstream os; int i = 12; os << i; cout << "the data is " + os.str() << endl; }
输出结果:
1
the data is 12
string转int
使用stoi/stol/stoll
1 2 3 4 5 6 7 8 9 10 11 12
int stoi (const string& str, size_t* idx = 0, int base = 10);
idx: Pointer to an object of type size_t, whose value is set by the function to position of the next character in str after the numerical value. This parameter can also be a null pointer, inwhichcase it is not used.