C++ string 转整数

使用 sstream 完成转换,ios

 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 对象屡次使用就要注意状态的清理,ui

 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。spa

缘由是第一次 ss >> integer 执行以后,ss 就被置上了 eof 标志,因此,第二次执行 ss >> integer 时,是不会输出的,integer 中保留了原来的 1234。下面的代码可以正确执行,code

#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 中原有的数据,使用下面的方法就能够保证正确执行,blog

ss.str("");        // 重置缓冲区数据
ss.clear();        // 不是必须的,可是保险起见

因此咱们发现不少地方单独使用 ss.str("") 后续并无获得正确输出,那就极可能是状态标志没有清除,而单独使用 ss.clear() 达不到清除缓冲区数据的目的。ci

相关文章
相关标签/搜索