📜  C++中的std :: stoul和std :: stoull

📅  最后修改于: 2021-05-30 18:56:54             🧑  作者: Mango

std :: stoul

将字符串转换为无符号整数。解析str并将其内容解释为指定基数的整数,并将其作为无符号long值返回。

unsigned long stoul 
(const string&  str, size_t* idx = 0, int base = 10);
Parameters :
str : String object with the 
representation of an integral number.
idx : Pointer to an object of type size_t, 
whose value is set by the function to position of the 
next character in str after the numerical value.
This parameter can also be a null pointer, in which case
it is not used.
base : Numerical base (radix) that determines
the valid characters and their interpretation.
If this is 0, the base used is determined by the format in
the sequence.Notice that by default this argument is 10, not 0. 

std :: stoull

将字符串转换为unsigned long long。解析str并将其内容解释为指定基数的整数,并将其作为unsigned long long类型的值返回。

unsigned long long stoull 
(const string&  str, size_t* idx = 0, int base = 10);
Parameters :
str : String object with the representation 
of an integral number.
idx : Pointer to an object of type size_t,
whose value is set by the function to position of the next 
character in str after the numerical value. This parameter can 
also be a null pointer, in which case it is not used.
base : Numerical base (radix) that determines 
the valid characters and their interpretation.
If this is 0, the base used is determined by the format in the
sequence. Notice that by default this argument is 10, not 0. 

例子:

Input : FF
Output : 255

Input : FFFFF
Output : 
// CPP code to convert hexadecimal
// string to int
#include 
using namespace std;
  
int main()
{
    // Hexadecimal string
    string str = "FF";
  
    // Converted integer
    unsigned long num = stoul(str, nullptr, 16);
  
    // Printing the integer
    cout << num << "\n";
  
    // Hexadecimal string
    string st = "FFFFFF";
  
    // Converted long long
    unsigned long long val = stoull(st, nullptr, 16);
  
    // Printing the long long
    cout << val;
    return 0;
}

输出:

255
16777215

另一个示例:比较两个包含十六进制值的字符串的程序
这里使用stoul ,但在数字超过无符号长值的情况下,将使用stoull

// CPP code to compare two
// hexadecimal string
#include 
using namespace std;
  
int main()
{
    // Hexadecimal string
    string s1 = "4F";
    string s2 = "A0";
  
    // Converted integer
    unsigned long n1 = stoul(s1, nullptr, 16);
    unsigned long n2 = stoul(s2, nullptr, 16);
  
    // Compare both string
    if (n1 > n2)
        cout << s1 << " is greater than " << s2;
    else if (n2 > n1)
        cout << s2 << " is greater than " << s1;
    else
        cout << "Both " << s1 << " and " << s2 << " are equal";
    return 0;
}

输出:

A0 is greater than 4F
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”