zoukankan      html  css  js  c++  java
  • 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() 达不到清除缓冲区数据的目的。

  • 相关阅读:
    Mysql::Error: Commands out of sync; you can't run this command now: SHOW TABLES解决方案
    mysql安装失败Error Nr. 1045
    TermServDevices 报错【远程服务使用者必读】
    数据库出现“提取逻辑页失败”
    Ruby学习——数据库操作
    VS2008 安装失败
    Ubuntu Server 安装图解
    C#的Enum——枚举
    SQLServer2005数据库被置为“可疑”
    ROR之include、extend、send对module、class进行扩展
  • 原文地址:https://www.cnblogs.com/wendellyi/p/4605959.html
Copyright © 2011-2022 走看看