C++ string 转整数
使用 sstream 完成转换,
1 #include <iostream> 2 #include <string> 3 #include <sstream> 4 #include <stdint.h> 5 6 int main () 7 { 8 std::string str_integer; 9 uint64_t integer; 10 11 std::getline(std::cin, str_integer); 12 std::stringstream ss; 13 ss.str(str_integer); 14 ss >> integer; 15 std::cout << __LINE__ << ":" << integer << std::endl; 16 17 return 0; 18 }
一次性转换较为容易,但是如果 std::stringstream 对象多次使用就要注意状态的清理,
1 #include <iostream> 2 #include <string> 3 #include <sstream> 4 #include <stdint.h> 5 6 int main () 7 { 8 std::string str_integer; 9 uint64_t integer; 10 std::stringstream ss; 11 12 str_integer = "1234"; 13 ss.str(str_integer); 14 ss >> integer; 15 std::cout << __LINE__ << ":" << integer << std::endl; 16 17 str_integer = "12345"; 18 ss.str(str_integer); 19 ss >> integer; 20 std::cout << __LINE__ << ":" << integer << std::endl; 21 22 return 0; 23 }
就会发现,第二次输出的值并不是 12345,而是 1234。
原因是第一次 ss >> integer 执行之后,ss 就被置上了 eof 标志,所以,第二次执行 ss >> integer 时,是不会输出的,integer 中保留了原来的 1234。下面的代码能够正确执行,
#include <iostream> #include <string> #include <sstream> #include <stdint.h> int main () { std::string str_integer; uint64_t integer; std::stringstream ss; str_integer = "1234"; ss.str(str_integer); ss >> integer; std::cout << __LINE__ << ":" << integer << std::endl; str_integer = "12345"; ss.str(str_integer); ss.clear(); // 加上这句就可以正确输出了 ss >> integer; std::cout << __LINE__ << ":" << integer << std::endl; return 0; }
ss.clear() 就可以清除 eof 标志,ss >> integer 就能正确输出。
另外,如果想清除 stringstream 中原有的数据,使用下面的方法就可以保证正确执行,
ss.str(""); // 重置缓冲区数据 ss.clear(); // 不是必须的,但是保险起见
所以我们发现很多地方单独使用 ss.str("") 后续并没有得到正确输出,那就很可能是状态标志没有清除,而单独使用 ss.clear() 达不到清除缓冲区数据的目的。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· Ollama——大语言模型本地部署的极速利器
· 使用C#创建一个MCP客户端
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· Windows编程----内核对象竟然如此简单?
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用