zoukankan      html  css  js  c++  java
  • int和string的相互装换 (c++)

    int和string的相互装换 (c++)


    int转换为string

    • 第一种方法
      to_string函数,这是c++11新增的函数
    string to_string (int val);
    string to_string (long val);
    string to_string (long long val);
    string to_string (unsigned val);
    string to_string (unsigned long val);
    string to_string (unsigned long long val);
    string to_string (float val);
    string to_string (double val);
    string to_string (long double val)

    这个函数还是非常的方便的

    int a = 0;
    cout << to_string(a) + "这是个字符串"<< endl;
    
    输出时会输出 "0这是个字符串" 
    • 第二种方法
      借助字符串流,标准库定义了三种类型字符串流:istringstream,ostringstream,stringstream
      看名字就知道这几种类型和iostream中的几个非常类似,分别可以读、写以及读和写string类型,它们也确实是从iostream类型派生而来的。
      要使用它们需要包含sstream头文件。
    include<sstream>
    
    int a = 0;
    string b;
    ostringstream os;//定义一个string输出流
    os << a;//将a输出到string流中
    b = a.str();

    注意ostringstream 流只能单次使用,即一次只能将一个int变量输入转为string变量输出,不可以重复使用

    string型转int型

    • 第一种方法
      采用标准库中atoi函数,需要文件头 < stdlib.h>
    string s = "888";   
    int a = atoi(s.c_str());  

    同样的,还有浮点型atof(),long long 型atoll()等等

    • 第二种方法
      C++11中的stoi
    string s = "888";  
    int n = stoi(str);  

    同样的还有stol,stoll等等函数。

    • 第三种方法
      借助字符串流,这个可以int转string,可以string转int
    include<sstream>
    
    istringstream is("888"); //构造输入字符串流,流的内容初始化为“12”的字符串   
    int i;   
    is >> i; //从is流中读入一个int整数存入i中  

    和上面一样,注意ostringstream 流只能单次使用

  • 相关阅读:
    AGC037F Counting of Subarrays
    AGC025F Addition and Andition
    CF506C Mr. Kitayuta vs. Bamboos
    AGC032D Rotation Sort
    ARC101F Robots and Exits
    AGC032E Modulo Pairing
    CF559E Gerald and Path
    CF685C Optimal Point
    聊聊Mysql索引和redis跳表
    什么是线程安全
  • 原文地址:https://www.cnblogs.com/neverth/p/11760946.html
Copyright © 2011-2022 走看看