栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++string类型和int类型的相互转换

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++string类型和int类型的相互转换

string 转换到int型

如果转换的是单个数字

   string s = "1234";
    s += "null";
    std::cout << s[1] << std::endl; //用[]重载得到的元素是char类型的一个元素
    auto b = s[1];//得到一个字符
    std::cout < 

同时转换多位数字

  • 使用stoi(),注意接受的参数类型是string
string s = "1234";
int i_from_s = stoi(s);
  • atoi() ,注意接受的参数类型是const char*
int i_from_s = atoi(s.c_str());//如果直接放s就会出错


int型转换到string

string to_string (int val);

int i=123;
string s=to_string(i);

补充:使用数据流进行转换
相比c库的转换,它更加安全,自动和直接。

#include 
#include 
#include  

int main()
{
    std::stringstream stream;
    std::string result;
    int i = 1000;
    stream << i; //将int输入流
    stream >> result; //从stream中抽取前面插入的int值
    std::cout << result << std::endl; // print the string "1000"
} 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/649050.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号