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

更新於: 2019-07-30

2K+ 瀏覽量

開啟你的職業生涯

完成課程獲得認證

立即開始
廣告