zoukankan      html  css  js  c++  java
  • string类型和int类型之间的转换

    一、string转int

    1. 使用string流

    /* 字符串转整型 */
    /*
     * istringstream:从 string 读取数据 
     * ostringstream:向 string 写入数据 
     * stringstream:既可从 string 读数据,也可向 string 写数据
     */ 
    void StrToInt(const string &s)
    {
    	int num = 0;
    	stringstream ss;
    	ss << s;
    	ss >> num;
    	cout << num << endl;
    }
    

      

    2. 采用标准库中 atoi 函数

    /* 字符串转整型 */
    void StrToInt(const string &s)
    {
    	int num = 0;
    	// 将string类型先转化为const char*类型 
    	const char *str = s.c_str();
    	num = atoi(str);
    	cout << num << endl;
    }
    

    3. 采用 stoi 函数

    /* 字符串转整型 */
    /*
     * 注:某些老版本的string不支持该函数 
     * 原型:int stoi (const string &str, size_t *idx = 0, int base = 10); 
     */ 
    void StrToInt(const string &s)
    {
    	int num = 0;
    	num = stoi(s);	// 等价于stoi(s, 0, 10); 
    	cout << num << endl;
    }
    

      

    二、int转string

    1. 使用string流

    /* 整型转字符串 */
    void IntToStr(int i)
    {
    	string s;
    	stringstream ss;
    	ss << i;
    	ss >> s;
    	cout << s << endl; 
    }
    

      

    2. 使用 sprintf 函数

    /* 整型转字符串 */
    /*
     * 原型:int sprintf (char *buffer, const char *format, [argument]...); 
     */ 
    void IntToStr(int i)
    {
    	string s;
    	char *str;
    	sprintf(str, "%d", i);
    	s = str;
    	cout << s << endl; 
    }
    

      

    3. 使用 to_string 函数

    /* 整型转字符串 */
    /*
     * 原型:string to_string (int val);
     */ 
    void IntToStr(int i)
    {
    	string s;
    	s = to_string(i);
    	cout << s << endl; 
    }
    

      

      

  • 相关阅读:
    python list介绍
    python unittest模块
    python 贪婪算法
    python 动态规划:背包问题
    汇编语言 基础知识(王爽)
    python 迪克斯特拉(Dijkstra)
    python 广度优先查找 (最短路径)
    Python 快速排序
    python 分而治之 找零数量 最小组合
    移动端的头部标签和 meta
  • 原文地址:https://www.cnblogs.com/xzxl/p/9605097.html
Copyright © 2011-2022 走看看