ใน C++ ใช้ std::ostringstream (จาก <sstream>) แทน sprintf() เพื่อจัดรูปแบบสตริงอย่างปลอดภัยและยืดหยุ่น
โค้ดตัวอย่าง
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main() {
ostringstream os;
os << "Store int: " << 50 << " and double: " << 52.32;
string my_str = os.str(); // แปลง stream เป็น string
cout << my_str;
}
ผลลัพธ์
Store int: 50 and double: 52.32
ข้อดีของ ostringstream
- Type-safe: ไม่ต้องระบุ format specifier (%d, %f)
- Extensible: รองรับ user-defined types ที่ overload operator<<
- ไม่มี buffer overflow risk
- สามารถใช้ manipulators (hex, setprecision, etc.)
C++20 เพิ่ม std::format ซึ่งคล้าย sprintf แต่ type-safe และทันสมัยกว่า