21xrx.com
2024-09-20 00:10:22 Friday
登录
文章检索 我的文章 写文章
C++ string转换为int
2023-06-30 06:28:53 深夜i     --     --
C++ string 转换 int

在C++程序中,经常需要将字符串类型的数字转换为整数类型以便进行数值计算或比较操作。下面是一种简单的方法可以实现C++ string转换为int。

首先需要包含头文件 ,这里为了方便使用了整个namespace std。


#include <iostream>

#include <cstdlib>

using namespace std;

然后,定义一个字符串变量str,并将需要转换的数字字符串赋给它。


string str = "1234";

接下来,可以使用函数 atoi() 来将字符串转换为整数类型,如下所示:


int num = atoi(str.c_str());

在这里,函数c_str()将string类型的str转换为C-style的字符串,即char类型的指针,参数传入atoi()函数中,实现字符串转为整数类型。

最终,输出转换后的整数值。


cout << "The converted integer is: " << num << endl;

完整代码如下:


#include <iostream>

#include <cstdlib>

using namespace std;

int main()

{

  string str = "1234";

  int num = atoi(str.c_str());

  cout << "The converted integer is: " << num << endl;

  return 0;

}

输出结果为:


The converted integer is: 1234

可以看到,使用该方法,C++中string类型的字符串可以很方便的转换为整数类型,方便进行数值计算和比较操作。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复