数值转换为字符串使用to_string()方法可以将各种数值类型转换为字符串类型这是一个重载函函数声明位于头文件中函数原型如下// 头文件 string string to_string (int val); string to_string (long val); string to_string (long long val); string to_string (unsigned val); string to_string (unsigned long val); string to_string (unsigned long long val); string to_string (float val); string to_string (double val); string to_string (long double val);用例#include iostream #include string using namespace std; //数值传字符串类型 void numberToString() { long double dd 3.1315926789; string pi pi is to_string(dd); string love love is to_string(13.14); cout pi endl; cout love endl endl; } int main() { numberToString(); system(pause); return 0; }输出结果pi is 3.131593 love is 13.140000字符串转换为数值C针对于不同的类型提供了不同的函数通过调用这些函数可以将字符串类型转换为对应的数值类型。// 定义于头文件 string int stoi( const std::string str, std::size_t* pos 0, int base 10 ); long stol( const std::string str, std::size_t* pos 0, int base 10 ); long long stoll( const std::string str, std::size_t* pos 0, int base 10 ); unsigned long stoul( const std::string str, std::size_t* pos 0, int base 10 ); unsigned long long stoull( const std::string str, std::size_t* pos 0, int base 10 ); float stof( const std::string str, std::size_t* pos 0 ); double stod( const std::string str, std::size_t* pos 0 ); long double stold( const std::string str, std::size_t* pos 0 );其中参数含义​ str要转换的字符串。​ pos传出参数记录从哪个字符开始无法继续进行转化比如 123a32就是在a的时候无法继续转换传出位置就是3即pos为a的地址。】​ base用于指明前面参数str的进制是说str是几进制转换后的结果都是10进制 若base为0则自动检测数值进制(若前缀为0则为八进制若前缀为0x或0X,则为十六进制否则为十进制。这些函数虽然都有多个参数但是除去第一个参数外其他都有默认值一般情况下使用默认值就能满足需求。关于函数的使用也给大家提供了一个例子示例代码如下#include iostream #include string using namespace std; //字符串转数值类型 void stringToNumber() { string str_dec 2022.02.04, Beijing Winter Olympics; string str_hex 40c3; string str_bin -10010110001; string str_auto 0x7f; size_t sz; // size_t是c标注库中定义的类型本质是无符号整型专门用来表示对象大小、内存大小、字符串长度、数组下标。 int i_dec stoi(str_dec, sz); int i_hex stoi(str_hex, nullptr, 16); int i_bin stoi(str_bin, nullptr, 2); int i_auto stoi(str_auto, nullptr, 0); //写0是让计算机自己推导。 cout ..... sz sz endl; cout str_dec : i_dec endl; cout str_hex : i_hex endl; cout str_bin : i_bin endl; cout str_auto : i_auto endl; } int main() { stringToNumber(); system(pause); return 0; }