您好,登錄后才能下訂單哦!
在 C++ 中,std::to_string()
函數(shù)是一種非常方便的將數(shù)字類(lèi)型轉(zhuǎn)換為字符串的方法
#include<iostream>
#include<string>
int main() {
int num = 42;
std::string str_num = std::to_string(num);
std::cout << "The integer is: "<< num<< std::endl;
std::cout << "The string representation of the integer is: "<< str_num<< std::endl;
return 0;
}
這個(gè)示例中,我們使用 std::to_string()
函數(shù)將整數(shù) num
轉(zhuǎn)換為字符串 str_num
。然后,我們分別輸出整數(shù)和字符串表示。
需要注意的是,std::to_string()
函數(shù)僅適用于 C++11 及更高版本的編譯器。如果你使用的是較舊的編譯器,可以考慮使用其他字符串轉(zhuǎn)換方法,例如使用 std::ostringstream
類(lèi):
#include<iostream>
#include <sstream>
#include<string>
int main() {
int num = 42;
std::ostringstream oss;
oss<< num;
std::string str_num = oss.str();
std::cout << "The integer is: "<< num<< std::endl;
std::cout << "The string representation of the integer is: "<< str_num<< std::endl;
return 0;
}
在這個(gè)示例中,我們使用 std::ostringstream
類(lèi)將整數(shù) num
轉(zhuǎn)換為字符串 str_num
。然后,我們分別輸出整數(shù)和字符串表示。這種方法適用于 C++98 及更高版本的編譯器。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。