如何將 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