我有一个来自 strtok()
的 token ,我想使用 atoi()
将其转换为整数并放置在数组中。但是,我遇到了困难。
char string[LMAX];
int array[LMAX];
int number;
char *token = NULL;
int count = 0;
FILE *fp;
fp = fopen("test.txt","r");
while(fgets (string, LMAX, fp) != NULL) {
//Reading the file, line by line
printf("%s", string);
token = strtok(string,",");
array[count++] = atoi(token);
//printf("%d",array[count]);
while(token=strtok(NULL,";,")){
number = atoi(token);
array[count++] = number;
printf("%d",array[count++]);
}
}
number
的类型为 int
,该数组也初始化为 int
数组。
当我运行以下代码时,我打印出全 0,但有趣的是,当我将 printf("%d", number);
替换为 printf("%d", atoi(token));
,我得到了正确的输出。我希望能够实际存储 atoi(token),但它不允许我这样做。
任何帮助都很棒
编辑:LMAX = 1024
最佳答案
It's only when I put
array[count++]
in the printf statement that it gives me 0's in the output
这是因为count++
有副作用。当您分配array[count++]
时然后打印array[count++]
,您没有打印相同的值,因为第二次索引会递增。
此外,计数将增加两次,因此 array
中的每个其他值将是未初始化的。
如果要打印刚刚存储在数组中的值,请使用 count-1
对于索引:
while(token=strtok(NULL,";,")){
number = atoi(token);
array[count++] = number;
printf("%d",array[count-1]);
}
关于c - 将 atoi() 返回的 int 插入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29248113/