您好,登錄后才能下訂單哦!
std::to_string
是 C++ 標(biāo)準(zhǔn)庫中的一個函數(shù),用于將數(shù)字類型(如 int、float、double 等)轉(zhuǎn)換為字符串。這個函數(shù)在頭文件中定義,因此在使用之前需要包含這個頭文件。以下是
std::to_string` 的一些常見用途:
#include<iostream>
#include<string>
int main() {
int num = 42;
std::string str_num = std::to_string(num);
std::cout << "Number as string: "<< str_num<< std::endl;
double dbl = 3.14;
std::string str_dbl = std::to_string(dbl);
std::cout << "Double as string: "<< str_dbl<< std::endl;
return 0;
}
#include<iostream>
#include<string>
int main() {
int a = 5;
int b = 7;
std::string result = "The sum of " + std::to_string(a) + " and " + std::to_string(b) + " is " + std::to_string(a + b) + ".";
std::cout<< result<< std::endl;
return 0;
}
#include<iostream>
#include<string>
#include <iomanip>
int main() {
double pi = 3.141592653589793;
std::string formatted_pi = std::to_string(pi);
formatted_pi = formatted_pi.substr(0, formatted_pi.find('.') + 3); // Keep only two decimal places
std::cout << "Formatted PI: "<< formatted_pi<< std::endl;
return 0;
}
#include<iostream>
#include<string>
#include <stdexcept>
int main() {
std::string input;
std::cout << "Enter a number: ";
std::cin >> input;
try {
int num = std::stoi(input);
std::cout << "You entered the integer: "<< num<< std::endl;
} catch (const std::invalid_argument& e) {
std::cout << "Invalid input: not an integer."<< std::endl;
} catch (const std::out_of_range& e) {
std::cout << "Invalid input: number is too large."<< std::endl;
}
return 0;
}
請注意,std::to_string
只能處理基本數(shù)據(jù)類型。對于自定義類型,你可能需要實現(xiàn)自己的字符串轉(zhuǎn)換函數(shù)。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。