简体   繁体   English

C语言中的strtok和int vs char

[英]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. 我正在学习如何对char数组进行升华,并且需要执行将数字和字符串拆分为不同变量并将其打印出来的操作。 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? 这是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" . 如果输入"123:foobar"作为输入,则指针n指向字符串 "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. 当您将指针转换为整数时,整数的值就是变量n的值,该变量n是由strtok返回的字符串在内存中的地址。

If you want to convert a string containing a number to an actual number, you should use eg the strtol function: 如果要将包含数字的字符串转换为实际数字,则应使用例如strtol函数:

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

This line is incorrect: 这行是不正确的:

int num = (int)n;

Is this the address to the int? 这是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). 不,它是存储整数的字符表示形式的位置处的字符缓冲区的地址,并重新解释为int (即,它可能是截断的地址,几乎没有意义的数字)。

You can convert it to int either by parsing the value, or using atoi : 您可以通过解析值或使用atoi将其转换为int:

int num = atoi(n);

Demo. 演示

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

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