1

在学习c++的stoi函数时,遇到第二个参数不明白如何正确使用

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

后查找资料如下:
image.png
所以第二个参数的使用分两种情况:

情况1:用0或者nullptr,表示不使用该参数(比较常见)
情况2:放置一个size_t类型的指针,str调用stoi函数后,该指针指向str中第一个不为数字的下标

对情况2举个栗子:

#include<iostream>
#include<string>

using namespace std;
int main() {
    string s = "1345s3544";
    size_t n ;
    std::size_t* pos=&n;
    int m = stoi(s,pos,10);
    cout << *pos;
}

最终输出结果为4
image.png


元海
4 声望0 粉丝