使用字符指针将字符串转换为整数的atoi函数

3

这是我编写的将字符串在 c 语言中分割的代码。然后,我想返回由 char 指针指向的第一个整数值。

#include<stdio.h>
void main(){
    int month[12]={0};
    char buf[]="1853 was the year";
        char *ptr;
        ptr = strtok(buf," ");
        printf("%s\n",ptr);
        int value = atoi(*ptr);
        printf("%s",value);
} 

编辑:它给了我分段错误。

问题是它打印出1853年,但我想将其转换为整数格式。如何使用指针将该值检索为整数?


注意:strtonum是atoi/atol的“安全鲁棒”版本。 - Finslicer
注意:main() 返回 int,并且接受 (void)(int, char **) - unwind
3个回答

5

您在此处试图将整数用作字符串:

    printf("%s",value);

你应该做的是

    printf("%d",value);

编辑:是的,还需要执行 int value = atoi(ptr);,正如另一个答案中所添加的。

main 函数应该是 int 类型,而不是 void。

此外,您使用的编译器是什么?在尝试编译您的代码时(添加一些包含文件后),我使用 gcc 4.6 得到了这些错误和警告:

ptrbla.C:5:11: error: ‘::main’ must return ‘int’
ptrbla.C: In function ‘int main()’:
ptrbla.C:11:30: error: invalid conversion from ‘char’ to ‘const char*’ [-fpermissive]
/usr/include/stdlib.h:148:12: error:   initializing argument 1 of ‘int atoi(const char*)’ [-fpermissive]
ptrbla.C:12:26: warning: format ‘%s’ expects argument of type ‘char*’, but argument 2 has type ‘int’ [-Wformat]

我认为大多数编译器都能提供其中至少一些功能。


3
    int value = atoi(ptr);

无需解引用,atoi() 需要一个 const char*,而不是一个 char
    printf("%d",value);

使用%d%i打印整数,%s仅用于字符串。


顺便提一下,也许你想使用strtol

char buf[]="1853 was the year";
char* next;
long year = strtol(buf, &next, 10);

printf("'%ld' ~ '%s'\n", year, next);
// 'year' is 1853
// 'next' is " was the year"

比我晚8秒,但是回答更详细。 - ugoren

0

使用:

int value = atoi(ptr);

atoi 应该接收一个字符指针,这就是 ptr 的作用。在这种情况下,*ptr 是第一个字符 - 1,无论如何都不是指针,因此对于 atoi 是无用的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接