C++ 中的 strtol() 函数
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() {
//Define two string
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() {
//Define two string
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。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP