c - C 中的 strtok 和 int 与 char

标签 c pointers casting strtok

我正在学习如何分隔字符数组,我需要执行一个操作,将数字和字符串拆分为不同的变量并将它们打印出来。我相信我已经很接近了,但是当打印出我的号码时,我得到了疯狂的数字。这是int的地址吗?任何意见是极大的赞赏!我的代码和输入/输出:

    #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);
    }

最佳答案

此行不正确:

int num = (int)n;

Is this the address to the int?

不,它是字符缓冲区的地址,位于存储整数字符表示的位置,重新解释为 int(即它可能是截断的地址,使其成为几乎是一个毫无意义的数字)。

您可以通过解析值或使用 atoi 将其转换为 int:

int num = atoi(n);

Demo.

关于c - C 中的 strtok 和 int 与 char,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25809122/

相关文章:

c - 使用存储在 C 结构中的变量引用结构的成员

c - 为什么只输出字符 'u'

c - 不懂简单的C程序if/else结果

C: 函数接收到的字符串似乎总是有 4 个空格

php - JS 对象 -> 从 jquery ajax 提交 JSON -> php 迭代

c++ - 方法处理程序的隐式转换?

c++ - 向上转换时的隐式转换与 static_cast

c - 使用C替换具有更高性能的最佳方法是什么?

C char*, char**, char***, 打印解难

c - 在 C 中释放其他变量类型