c语言字符串转long long int
时间: 2023-11-28 18:04:37 浏览: 45
在C语言中,可以使用`strtol()`函数将字符串转换为长整型数(long long int)。`strtol()`函数的原型为:`long long int strtoll(const char *str, char **endptr, int base)`。其中,`str`为要转换的字符串,`endptr`为第一个不能转换的字符的指针,`base`为字符串`str`所采用的进制。`strtol()`函数会将参数`str`字符串根据参数`base`来转换成长整型数(long long int)。参数`base`范围从2至36,或0。参数`base`代表`str`采用的进制方式,如`base`值为10则采用10进制,若`base`值为16则采用16进制等。`strtol()`函数会扫描参数`str`字符串,跳过前面的空白字符(例如空格,tab缩进等,可以通过`isspace()`函数来检测),直到遇上数字或正负符号才开始做转换,再遇到非数字或字符串结束时('\0')结束转换,并将结果返回。
示例代码如下所示:
```c
#include <stdio.h>
#include <stdlib.h>
int main()
{
char str[] = "123456789";
char *endptr;
long long int num = strtoll(str, &endptr, 10);
printf("%lld\n", num);
return 0;
}
```
相关问题
c语言字符串怎么转换为long类型
可以使用C标准库函数`atol()`将字符串转换为long类型。
函数原型如下:
```c
long int atol(const char *str);
```
其中,`str`是需要转换的字符串,函数会返回转换后的long类型数据。
示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
int main() {
char str[] = "12345";
long num = atol(str);
printf("%ld\n", num);
return 0;
}
```
输出结果为:
```
12345
```
C语言字符串转数字函数
C语言中有多种方法可以将字符串转换为数字。其中一种常用的方法是使用标准库函数`atoi()`、`atol()`、`atof()`等。
1. `atoi()`: 字符串转换为整型数。
```c
#include <stdlib.h>
int atoi(const char *str);
```
示例:
```c
#include <stdio.h>
#include <stdlib.h>
int main() {
char str[] = "12345";
int num = atoi(str);
printf("Converted number: %d\n", num);
return 0;
}
```
2. `atol()`: 字符串转换为长整型数。
```c
#include <stdlib.h>
long int atol(const char *str);
```
示例:
```c
#include <stdio.h>
#include <stdlib.h>
int main() {
char str[] = "1234567890";
long int num = atol(str);
printf("Converted number: %ld\n", num);
return 0;
}
```
3. `atof()`: 字符串转换为双精度浮点数。
```c
#include <stdlib.h>
double atof(const char *str);
```
示例:
```c
#include <stdio.h>
#include <stdlib.h>
int main() {
char str[] = "3.14";
double num = atof(str);
printf("Converted number: %f\n", num);
return 0;
}
```
另外,也可以使用更灵活的函数`strtol()`和`strtod()`进行字符串转换。这些函数提供了更多的选项和错误处理机制。更多详细信息可以参考C语言标准库的相关文档。