標籤:
使用 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() 本是就達不到清楚緩衝區資料的目的,是錯的。
C++ string 轉整數