如何将 C++ 中的 std::string 和 int 拼接起来?
在这个程序中,我们将看到如何将字符串和整数类型数据连接在 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
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP