阅读量:116
C语言函数strtol和strtok的用法如下:
- strtol函数用于将字符串转换为长整型数。其函数原型如下:
long strtol(const char *nptr, char **endptr, int base)
- nptr:要转换的字符串。
- endptr:指向转换完成后第一个无效字符的指针,可为NULL。
- base:进制数,可选值为2-36之间的任意值,或者0。
示例代码:
#include
#include
int main() {
char str[] = "12345abc";
char *endptr;
long num = strtol(str, &endptr, 10);
if (endptr == str) {
printf("No digits were found.\n");
}
else {
printf("The number is: %ld\n", num);
printf("The next character is: %s\n", endptr);
}
return 0;
}
- strtok函数用于分割字符串。其函数原型如下:
char *strtok(char *str, const char *delim)
- str:要分割的字符串,第一次调用时传入,以后调用传入NULL。
- delim:分割字符串的分隔符。
示例代码:
#include
#include
int main() {
char str[] = "Hello,World,How,Are,You";
char *token;
token = strtok(str, ",");
while (token != NULL) {
printf("%s\n", token);
token = strtok(NULL, ",");
}
return 0;
}