该strol()
函数用于将字符串转换为长整数。它将指针设置为指向最后一个字符之后的第一个字符。语法如下。此功能存在于cstdlib库中。
long int strtol(const char* str, char ** end, int base)
此函数接受三个参数。这些参数如下-
str:这是字符串的开头。
str_end:函数将str_end设置为最后一个有效字符之后的下一个字符(如果有),否则为null。
base:指定基数。基本值可以是(0,2,3,…,35,36)
此函数返回转换后的long int。当字符指向NULL时,它返回0。
#include <iostream> #include<cstdlib> using namespace std; main() { //定义两个字符串 char string1[] = "777HelloWorld"; char string2[] = "565Hello"; char* End; //The end pointer int base = 10; int value; value = strtol(string1, &End, base); cout << "The string Value = " << string1 << "\n"; cout << "Long Long Int value = " << value << "\n"; cout << "End String = " << End << "\n"; //remaining string after long long integer value = strtol(string2, &End, base); cout << "\nThe string Value = " << string2 << "\n"; cout << "Long Long Int value = " << value << "\n"; cout << "End String = " << End; //remaining string after long long integer }
输出结果
The string Value = 777HelloWorld Long Long Int value = 777 End String = HelloWorld The string Value = 565Hello Long Long Int value = 565 End String = Hello
现在让我们看一下具有不同基值的示例。这里的底数是16。通过采用给定底数的字符串,它将以十进制格式打印。
#include <iostream> #include<cstdlib> using namespace std; main() { //定义两个字符串 char string1[] = "5EHelloWorld"; char string2[] = "125Hello"; char* End; //The end pointer int base = 16; int value; value = strtol(string1, &End, base); cout << "The string Value = " << string1 << "\n"; cout << "Long Long Int value = " << value << "\n"; cout << "End String = " << End << "\n"; //remaining string after long long integer value = strtol(string2, &End, base); cout << "\nThe string Value = " << string2 << "\n"; cout << "Long Long Int value = " << value << "\n"; cout << "End String = " << End; //remaining string after long long integer }
输出结果
The string Value = 5EHelloWorld Long Long Int value = 94 End String = HelloWorld The string Value = 125Hello Long Long Int value = 293 End String = Hello
这里的字符串包含5E,因此其值为十进制的94,第二个字符串包含125。十进制的293。