字符串与数字双向转换
新C++中已经有函数实现此类功能。
- 数字转为字符串
#include <sstream> //include this to use string streams #include <string> int main() { int number = 1234; std::ostringstream ostr; //output string stream ostr << number; //use the string stream just like cout, //except the stream prints not to stdout but to a string. std::string theNumberString = ostr.str(); //the str() function of the stream //returns the string. //now theNumberString is "1234" }
- 字符串转为数字
#include <sstream> #include <string> int main() { std::string inputString = "1234 12.3 44"; std::istringstream istr(inputString); int i1, i2; float f; istr >> i1 >> f >> i2; //i1 is 1234, f is 12.3, i2 is 44 }
参见:
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步