ในโปรแกรมนี้ เราจะมาดูวิธีการเชื่อมข้อมูลประเภทสตริงและจำนวนเต็มใน C++ ในการต่อข้อมูลสตริงและจำนวนเต็ม เราต้องแปลงจำนวนเต็มเป็นสตริงก่อน ในการแปลงเราใช้สตริงสตรีม นี้มีคุณสมบัติบางอย่าง มันใช้ตัวเลขหรือสตริงแล้วทำให้เป็นสตริง
Input: String “str” and Number 10 Output: Concatenated string “str10”
อัลกอริทึม
Step 1: Take string and number Step 2: Convert number to string Step 3: Concatenate them Step 4: End
โค้ดตัวอย่าง
#include <iostream>
#include <sstream>
using namespace std;
string int_to_str(int x) {
stringstream ss;
ss << x;
return ss.str();
}
int main() {
string my_str = "This is a string: ";
int x = 50;
string concat_str;
concat_str = my_str + int_to_str(x);
cout << concat_str;
} ผลลัพธ์
This is a string: 50