简体   繁体   English

使用char指针将atoi从string转换为Integer

[英]atoi from string to Integer using char pointer

Here is the code I have written which splits a string in c and then I want to return the first integer value pointed by the char pointer. 这是我编写的代码,它在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);
} 

EDIT:It gives me segmentation fault. 编辑:它给我分段错误。

The problem is it is printing 1853 as the year, But I want to convert this into integer format.How can i retrieve that value as an integer using the pointer? 问题是它打印1853作为年份,但我想将其转换为整数格式。如何使用指针将该值检索为整数?

you are here trying to use an integer as a string: 你在这里尝试使用整数作为字符串:

    printf("%s",value);

you should do 你应该做

    printf("%d",value);

Edit: yes, and also do int value = atoi(ptr); 编辑:是的,也做int value = atoi(ptr); as added in another answer. 在另一个答案中添加。

main should also be int, not void. main也应该是int,而不是void。

Also, what compiler are you using? 另外,你使用什么编译器? With gcc 4.6 I got these errors and warnings when trying to compile your code (after adding some includes): 使用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]

I'd think you could get at least some of these from most compilers. 我认为你可以从大多数编译器中获得至少一些这些。

    int value = atoi(ptr);

No need to dereference, atoi() expects a const char* , not a char . 不需要取消引用, atoi()需要一个const char* ,而不是char

    printf("%d",value);

And you print an integer using %d or %i . 然后使用%d%i打印整数。 %s is for string only. %s仅用于字符串。


BTW, maybe you would like to use strtol instead 顺便说一句,也许你想用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"

Use: 使用:

int value = atoi(ptr);

atoi should get a character pointer, which is what ptr is. atoi应该得到一个字符指针,这就是ptr *ptr is the first character - 1 in this case, and anyway isn't a pointer, so it's unusable for atoi . *ptr是第一个字符 - 在这种情况下为1,并且无论如何不是指针,因此它对于atoi无法使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM