首頁  >  文章  >  後端開發  >  C++程式將int型別變數轉換為字串

C++程式將int型別變數轉換為字串

PHPz
PHPz轉載
2023-09-03 22:05:033716瀏覽

C++程式將int型別變數轉換為字串

C 中的整數類型變數能夠儲存預先定義範圍內的正整數值或負整數值。字串變數可以儲存字母、數字和特殊字元的序列。有許多用例需要從 int 轉換為 string。我們討論 3 種將整數變數轉換為字串的不同方法。

如果我們討論演算法,那就非常簡單了。我們在整數變數中取得輸入,然後將其轉換為字串變數。

使用 to_string 函數

C 中將整數值轉換為字串的最簡單方法是使用 to_string 函數。 to_string 函數預設可用;它接受一個整數值作為輸入並提供一個字串值作為輸出。我們來看看下面的例子來進一步理解這個概念。

文法

int ip = <integer value>;
string op = std::to_string(ip);

演算法

  • 在整數變數中取得輸入。
  • 使用 to_string 函數將整數值轉換為字串並將其儲存在字串變數中。
  • 顯示結果。

範例

#include <iostream>
using namespace std;
string solve(int ip) {
   //using the to_string function
   return to_string(ip);
}
int main()
{
   int ip = 10;
   string op = solve(ip);
   cout<< "The input value is: " << ip << endl;
   cout<< "The output value is: " + op << endl;
   return 0;
}

輸出

The input value is: 10
The output value is: 10

在此範例中,我們使用 to_string 函數將整數值轉換為字串。顯示輸出時需要注意的一點;我們使用插入運算子 (

使用 ostringstream

ostringstream 是包含字元序列的字串緩衝區。在該方法中,我們將整數值輸入到 ostringstream 物件中,然後將其格式化為字串。

文法

int ip = <integer value>;
ostringstream oss;
oss << ip;
string op = oss.str();

演算法

  • 在整數變數中取得輸入。
  • 將輸入整數變數傳遞給 ostringstream 物件。
  • 將 ostringstream 物件的字串表示形式指派給字串輸出變數。
  • 顯示結果。

範例

#include <iostream>
#include <sstream>

using namespace std;
string solve(int ip) {
   //using ostringstream
   ostringstream oss;
   oss << ip;
   return oss.str();
}

int main()
{
   int ip = 10;
   string op = solve(ip);

   cout<< "The input value after addition of 10 is: " << ip + 10 << endl;
   cout<< "The output value after addition of 10 is: " << op + "10" << endl;
   return 0;
}

輸出

The input value after addition of 10 is: 20
The output value after addition of 10 is: 1010

在前面的範例中,我們在輸入值中新增了一個整數值 10 以表示它是一個整數值,並在輸出值中新增了一個字串「10」以表示它是一個字串值。

使用 sprintf

sprintf 是 C 中的標準函式庫函數,它將格式化輸出傳送到字串 str。使用 sprintf 函數,我們可以將整數轉換為字串。

文法

int ip = <integer value>;
char str[100];
sprintf(str, "%d", ip);
string s = str;

演算法

  • 在整數變數中取得輸入。
  • 將輸入整數變數和字元緩衝區傳遞給 sprintf 函數。
  • 將字元緩衝區指派給結果字串變數。
  • 顯示結果。

範例

#include <iostream>
using namespace std;
string solve(int ip) {
   char str[100];
   sprintf(str, "%d", ip);
   string s = str;
   return s;
}

int main()
{
   int ip = 10;
   string op = solve(ip);
   cout<< "The input value after addition of 10 is: " << ip + 10 << endl;
   cout<< "The output value after addition of 10 is: " << op + "10" << endl;
   return 0;
}

輸出

The input value after addition of 10 is: 20
The output value after addition of 10 is: 1010

這個例子和前面的例子類似,唯一不同的是轉換方法。要使用 sprintf,我們不需要匯入任何其他函式庫。

結論

我們可能需要在各種場合將整數轉換為字串,主要是使用僅支援字串參數的函數從計算中輸出資料。我們討論的第一種方法是最簡單的,但它可以從 C 11 版本開始使用。使用 ostringstream 的第二種方法需要導入另一個庫 sstream,而使用 sprintf 的最後一種方法需要輔助字元或字串緩衝區來將整數值轉換為字串。最快的方法是第一種,但如果由於編譯器過時而不起作用,那麼其他兩種方法應該可以。

以上是C++程式將int型別變數轉換為字串的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除