栏目分类:
子分类:
返回
文库吧用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
文库吧 > IT > 软件开发 > 后端开发 > Java

C++中将string 类型与int类型的相互转换

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

C++中将string 类型与int类型的相互转换

这里写目录标题
  • string 转换为int
    • 1.atoi
    • 2.strtol
    • 3.stoi
    • 4. stringstream
  • int 转换为string
    • 1.sprintf_s
    • 2.stringstream
    • 3.to_string

string 转换为int 1.atoi
#include
using namespace std;
int main()
{
	int x = 0;
	string str1 = "10";
	string str2 = "-10";
	string str3 = "10a";
	x = atoi(str1.c_str());
	cout << x << endl;
	x = atoi(str2.c_str());
	cout << x << endl;
	x = atoi(str3.c_str());
	cout << x << endl;
	return 0;
}

2.strtol

long int strtol (const char str, char* endptr, int base);

str 为要转换的字符串,endstr 为第一个不能转换的字符的指针,base 为字符串 str 所采用的进制。

 #include
using namespace std;
int main()
{
	int x = 0;
	string str1 = "10";
	string str2 = "-10";
	string str3 = "10a";
	x = strtol(str1.c_str(), nullptr, 10);
	cout << x << endl;
	x = strtol(str2.c_str(), nullptr, 10);
	cout << x << endl;
	x = strtol(str3.c_str(), nullptr, 10);
	cout << x << endl;

	return 0;
}

 

3.stoi

c11之后才有,需要引入 < string>

#include
#include
using namespace std;
int main()
{
	int x = 0;
	string str1 = "10";
	string str2 = "-10";
	string str3 = "10a";
	x = stoi(str1);
	cout << x << endl;
	x = stoi(str2);
	cout << x << endl;
	x = stoi(str3);
	cout << x << endl;

	return 0;
}

4. stringstream

需要引入< sstream>

#include
#include
using namespace std;
int stringToInt(const string& s)
{
	stringstream ss;
	int result;
	ss << s;
	ss >> result;
	return result;

}
int main()
{
	    string str1 = "10";
	    string str2 = "-10";
	    string str3 = "10a";
		cout << stringToInt(str1)< 
int 转换为string 
1.sprintf_s 
#include
using namespace std;
int main()
{
	int number = 10;
	char buff[128] = { 0 };
	sprintf_s(buff, 128, "%d",number);
	cout << buff << endl;

}

2.stringstream

需要引入

#include
#include
using namespace std;
int main()
{
	int number = 10;
	stringstream ss;
	ss << number;
	string str = ss.str();
	cout << str << endl;

};

3.to_string

c11之后才可用,需引入string

#include
#include
using namespace std;
int main()
{
	int number = 10;
	string str =to_string(number);
	cout << str << endl;

};

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

版权所有 (c)2021-2022 wk8.com.cn

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