C++字符串与整数的相互转换

30 篇文章 2 订阅

前言

题目大致为:

给一组数据,去掉里面的2,然后再返回结果

例如:

输入:{20, 66, 521, 2024}

输出:{0, 66, 51, 4}

思路是将数字转成字符串,然后去掉2,但是脑子没转过来,忘记接口了,用最原始方法转换的

字符串转整数

stoi

string类提供了一系列字符串转数字的接口(C++11引入):

文档:C++ Reference (cplusplus.com)

在这里插入图片描述

这里拿stoi举例:

int stoi (const string&  str, size_t* idx = nullptr, int base = 10);
int stoi (const wstring& str, size_t* idx = nullptr, int base = 10);
  • str:要转换的字符串
  • idx:结束未处理到的字符索引,默认为nullptr
  • base:数字进制,默认十进制
#include<iostream>
#include<string>
using namespace std;
int main()
{
	string str_dec = "1234, hello world";
	string str_hex = "40c3";
	string str_bin = "-110101";
	string str_auto = "0x7f";

	size_t sz;

	int i_dec = stoi(str_dec, &sz);
	int i_hex = stoi(str_hex, nullptr, 16);
	int i_bin = stoi(str_bin, nullptr, 2);
	int i_auto = stoi(str_auto,nullptr,0);	//自动识别

	cout << str_dec << ": " << i_dec << " + [" << str_dec.substr(sz) << "]" << endl;
	cout << str_hex << ": " << i_hex << endl;
	cout << str_bin << ": " << i_bin << endl;
	cout << str_auto << ": " << i_auto << endl;
}

isstringstream

从字符串流当中读取数据

文档:istringstream - C++ Reference (cplusplus.com)

#include <iostream>
#include <sstream>

int main() {
    std::string str = "123";
    std::istringstream iss(str);
    int num;
    iss >> num;
    if (iss.fail())
    {
        std::cerr << "failed" << std::endl;
    } else
    {
        std::cout << "Integer: " << num << std::endl;
    }
    return 0;
}

atoi

C语言也提供了转换接口:

在这里插入图片描述

atoi举例:

int atoi (const char * str);

将C风格的字符串转成整数,但是这个没有错误检查机制

#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
	char ch[] = "1234";
	string s = "5678";
	int n1 = atoi(ch);
	int n2 = atoi(s.c_str());
	cout << n1 << endl;
	cout << n2 << endl;
	return 0;
}

字符转整数

to_string

文档:to_string - C++ Reference (cplusplus.com)

在这里插入图片描述

#include<iostream>
#include<string>
int main()
{
	int a = 23456;
	std::string s = std::to_string(a);
	std::cout << s << std::endl;
	return 0;
}

stringstream

文档:stringstream - C++ Reference (cplusplus.com)

int main()
{
	int a = 1234;
	stringstream ss;
	
	//整数写进字符串流
	ss << a;

	//字符串流提取
	string s = ss.str();
	cout << s << endl;
	return 0;
}

sprintf

这是C语言提供的函数

#include <iostream>
#include <cstdio>

int main()
{
    int num = 123;
    char buffer[50];
    sprintf(buffer, "%d", num);
    std::string str(buffer);
    std::cout << "String: " << str << std::endl;
    return 0;
}

ASCII码转换

字符'0'的ASCII码是48
在这里插入图片描述

转换的时候加减48即可

int main()
{
	char c = '5';
	int c2i = c - 48;
	cout << c2i << endl;

	int n = 3;
	char i2c = n + 48;
	cout << i2c << endl;
	return 0;
}

数字字符部分ASCII码表:

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

加法器+

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值