简体   繁体   中英

strtok and int vs char in C

I am learning how to delimate char arrays and I need to do an operation where I split a number and string into different variables and print them out. I believe I am close but when printing out what should be my number I get crazy numbers. Is this the address to the int? Any advice is greatly appreciated! My code and input/output:

    #include <stdio.h>

    int main() {
        setbuf(stdout, NULL);
        char name[10];
        printf("Enter in this format, integer:name\n");
        fgets(name, 10, stdin);                            //my input was 2:brandon
        char *n = strtok(name, ":");
        int num = (int)n;
        char * order = strtok(NULL, ":");
        printf("%d,%s", num,order);                        //my output was 7846332,brandon
        return (0);
    }

If you give eg "123:foobar" as input, the pointer n points to the string "123" . When you cast the pointer to an integer, the value of the integer is the value of the variable n which is the address of where in memory the string returned by strtok is located.

If you want to convert a string containing a number to an actual number, you should use eg the strtol function:

int num = strtol(n, NULL, 10);

This line is incorrect:

int num = (int)n;

Is this the address to the int?

No, it is an address of the character buffer at the position where the character representation of your integer is stored, re-interpreted as an int (ie it may be a truncated address, making it pretty much a meaningless number).

You can convert it to int either by parsing the value, or using atoi :

int num = atoi(n);

Demo.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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