在此程序中,我们将看到如何在C ++中连接字符串和整数类型的数据。要连接字符串和整数数据,首先必须将整数转换为字符串。为了转换它,我们使用了stringstream。这提供了一些功能。它需要数字或字符串,然后使其成为字符串。
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