std::to_string
是 C++ 标准库中的一个函数,用于将数字类型(如 int、float、double 等)转换为字符串。这个函数在头文件中定义,因此在使用之前需要包含这个头文件。以下是
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
只能处理基本数据类型。对于自定义类型,你可能需要实现自己的字符串转换函数。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。