21xrx.com
2025-03-23 22:53:49 Sunday
文章检索 我的文章 写文章
C++中string类型转换成int类型的方法
2023-07-09 07:04:44 深夜i     59     0
C++ string 转换 int 方法

C++是一种非常流行和广泛使用的编程语言,它提供了一种强大的字符串类型string,同时也提供了丰富的类型转换方法。在C++编程中,将string类型转换为int类型是一种常见的需求,下面我们来介绍几种可行的方法。

1. 使用stoi函数

C++11中提供了一个很方便的函数stoi,可以将string类型转换为int类型。该函数的原型如下:

int stoi (const string& str, size_t* idx = 0, int base = 10);

参数解释:

- str:要转换的字符串。

- idx:可选参数,用来指出转换结束后的第一个无效字符位置。

- base:可选参数,指定进制,默认为10。

示例代码:

#include <iostream>
#include <string>
using namespace std;
int main()
{
  string str = "1234";
  int num = stoi(str);
  cout << "num is " << num << endl;
  return 0;
}

2. 使用sscanf函数

C标准库中提供了一个sscanf函数,可以从一个字符串中根据格式化字符串解析值。具体使用方式如下:

#include <cstdio>
int sscanf(const char * str, const char * format, ...);

示例代码:

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int main()
{
  string str = "1234";
  int num;
  sscanf(str.c_str(), "%d", &num);
  cout << "num is " << num << endl;
  return 0;
}

3. 使用stringstream

C++的标准库中也提供了stringstream类,可以方便地实现字符串和数值类型之间的转换。其基本用法如下:

#include <sstream>
stringstream ss;
ss << str;
int num;
ss >> num;

示例代码:

#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
  string str = "1234";
  stringstream ss;
  ss << str;
  int num;
  ss >> num;
  cout << "num is " << num << endl;
  return 0;

总结

以上三种方法都可以将string类型转换为int类型,选择合适的方法可以根据具体情况来定。虽然第二种方法使用的是C标准库的函数,但是还是可以在C++中使用,而且该方法对于一些特殊的格式有很好的适用性。建议在实际应用中根据需要选择使用。

  
  

评论区