C++程式:將int型變數轉換為字串
C++中的整數型別變數可以儲存正或負整數,其範圍預先定義。字串變數可以儲存一系列字母、數字和特殊字元。在許多用例中,需要將int轉換為字串。我們將討論三種不同的方法來將整數變數轉換為字串。
如果我們討論演算法,它非常簡單明瞭。我們將輸入儲存在一個整數變數中,然後將其轉換為字串變數。
使用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的方法需要一個輔助字元或字串緩衝區來將整數值轉換為字串。最快的方法是第一種,但是如果由於編譯器過舊而無法使用,則其他兩種方法應該可以工作。
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP