C++ string 轉整數

來源:互聯網
上載者:User

標籤:

使用 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 轉整數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.