我正在学习如何分隔字符数组,我需要执行一个操作,将数字和字符串拆分为不同的变量并将它们打印出来。我相信我已经很接近了,但是当打印出我的号码时,我得到了疯狂的数字。这是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);
关于c - C 中的 strtok 和 int 与 char,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25809122/