C++中string类型和int类型之间的相互转换【全网最全】

字符串操作是各种算法题中的常客,很多数据常常以字符串形式给出,其中有的需要自己转化成整数,而一些整型数据有时转换成字符串处理起来更加方便,比如判断一个整数是否是回文数,所以字符串和整数的转换是一些问题处理的基础步骤,C++ 在处理这类问题时并不像 Python 那样方便,但是也有许多方法能够实现。

一、string 转为int

1、使用 atoi 转换

#include <iostream>
#include <stdlib.h>

int main()
{
    std::string str = "668";
    std::cout << atoi(str.c_str());
    return 0;
}

atoi 函数的头文件是 stdlib.h,同样是一个C语言中的函数

2、 使用std::stoi

这个标准库是从C++11开始才有的
示例代码如下:

#include <iostream>
#include <string>

using namespace std;

int main()
{
	int x;
	string str = "-10";
	string str1 = "-10a";
	string str2 = "a10";
	x = stoi(str);
	cout << x << endl;
	x = stoi(str1);		 //stoi()函数遇到字母时会自动停下
	cout << x << endl;
	//x = stoi(str2);    //stoi()函数没有数字的话,程序虽然可以编译,但运行时会出错
	//cout << x << endl;
	return 0;
}

3、 通过 istringstream 转换

#include <iostream>
#include <sstream>

int main()
{
    std::string str = "668";
    int num = 0;

    std::istringstream ss(str);
    ss >> num;

    std::cout << num;
    return 0;
}

使用 istringstream 可以从字符流中读取整数,与 ostringstream 是一种相反的操作

4、使用 sscanf

sscanf 函数是 C 语言标准库中的函数,可以用于从一个格式化的字符串中提取数据。在 C++ 中,可以使用 sscanf 函数将字符串转换为整数。

下面是一个示例代码,展示如何使用 sscanf 将字符串转换为整数:

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <string>

int main() {
    std::string str = "12345";
    int num;

    if (sscanf(str.c_str(), "%d", &num) == 1) {
        std::cout << "Converted number: " << num << std::endl;
    } else {
        std::cout << "Failed to convert the string to an integer." << std::endl;
    }

    return 0;
}

在上面的代码中,我们将字符串 "12345" 存储在 str 变量中。然后,我们使用 sscanf 函数将字符串转换为整数,并将结果存储在 num 变量中。sscanf 函数的第一个参数是要转换的字符串(使用 c_str() 方法将 std::string 转换为 C 风格的字符串),第二个参数是格式化字符串 "%d",用于指定要提取的数据类型为整数。如果转换成功,sscanf 函数将返回成功转换的变量数目(在这个例子中为 1),否则返回值为 0。

以上代码的输出将是:

Converted number: 12345

请注意,sscanf 函数可以根据不同的格式化字符串提取不同类型的数据。如果你的字符串中包含其他数据类型,你可以相应地修改格式化字符串和变量的类型。

【注】如果你使用的是VS编译器,那么会报错说sscanf不安全,改为sscanf_s即可。

5、使用strtol

使用c标准库

#include <stdlib.h>
long int strtol(const char *nptr, char **endptr, int base);

示例代码:

#include <iostream>
#include <cstdlib>
#include <string>
 
int main()
{
  std::string text{"123"};
  errno = 0; // pre set to 0
  int number = (int)std::strtol(text.c_str(), nullptr, 10);
  if (errno == ERANGE) {
    // the number is too big/small
    // number = (int)LONG_MAX or (int)LONG_MIN
    std::cerr << "Too big or small: " << errno << "\n";
    return 1;
  } else if (errno) {
    // maybe EINVAL, E2BIG or EDOM
    // unable to convert to a number
    std::cerr << "ERROR: " << errno << "\n";
    return 1;
  }
  // TODO: you need to check whether the long to int overflow too if neccessary
  std::cout << number << "\n";
  return 0;
}

6、使用at()函数定位,先转为字符型,然后再转为int类型

#include <iostream>
#include <string>

using namespace std;

int main()
{
	string str = "a1b2c3";
	int i = str.at(1) - '0';
	cout << i << endl;
	return 0;
}

二、 int转为string

1、通过 std::to_string() 函数

#include <iostream>
#include <string> // 添加这个头文件

int main() {
    int num = 123;
    std::cout << std::to_string(num);
    return 0;
}

这种方式在 C++11 中才能使用,编译时记得加上 --std=c++11 的选项

2、通过 ostringstream

#include <iostream>
#include <sstream>

int main()
{
    int num = 123;
    std::ostringstream ss;
    ss << num;
    std::cout << ss.str();
    return 0;
}

这是一种通过字符流的方式将整数转换成字符串,这种方式在C++11之前也可以使用

3、通过 sprintf

#include <stdio.h>

int main()
{
    int num = 123;
    char buffer[256];
    sprintf(buffer, "%d", num);

    printf("%s", buffer);
    return 0;
}

【注】上述代码在VS编译器中运行时,会报sprintf不安全,换为sprintf_s即可

这是一种C语言中的转换方式,sprintf 也可以换成更安全的 snprintf 函数,如下所示。

#include <iostream>
#include <cstdio>

int main() {
	char buffer[100];
	int num = 123;

	// 使用 snprintf 将整数 num 格式化为字符串并存储在 buffer 中
	snprintf(buffer, sizeof(buffer), "%d", num);

	// 使用 std::cout 输出 buffer 中的内容
	std::cout << "buffer 中的内容是:" << buffer << std::endl;

	return 0;
}

  • 12
    点赞
  • 75
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值