C++中将int转变成string和string转变成int

本文介绍了C++中将整数转换为字符串和字符串转换为整数的方法,包括使用itoa函数进行整数到字符串的转换以及使用atoi和atoi函数进行字符串到整数的转换。此外,还展示了使用stringstream类进行更灵活的字符串操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

int to string

#include<iostream>
#include<string>
using namespace std;
int main()
{
    string s;
    char c[100];
    int m=199;
    itoa(m,c,10);
    s=c;
    s.insert(0,"zhang");
    cout<<s<<endl;
    return 0;


}

string to int

#include<iostream>
#include<string>
using namespace std;
int main()
{
    string s="56sd";
    int a=atoi(s.c_str());
    cout<<a<<endl;
    return 0;
}

 

 

另外一种方法,包含#include<sstream>,例如

#include<iostream>
#include<sstream>
#include<string>
using namespace std;
int main()
{
	stringstream s;
	string ss="234";
	s<<ss;
	s<<"abcd";


	string s0;
	int n;
	s>>n;
	s>>s0;

	cout<<n<<"  "<<s0<<endl;

	return 0;
}

  

转载于:https://www.cnblogs.com/xiaovlxx/p/4508907.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值