【问题标题】:inserting returned int from atoi() into array将 atoi() 返回的 int 插入数组
【发布时间】:2015-03-25 05:29:07
【问题描述】:

我有一个来自strtok() 的令牌,我想将其转换为整数并使用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

【问题讨论】:

  • count 未初始化?
  • 请发布您的完整代码。该错误超出了您发布的三行。
  • 数字变量的数据类型是什么。
  • "number" 是 int 类型
  • 这个问题不能用这个确切的代码重现(link to a demo)。

标签: c arrays atoi


【解决方案1】:

只有当我在 printf 语句中输入 array[count++] 时,它才会在输出中给我 0

这是因为count++ 有副作用。当您分配 array[count++] 然后打印 array[count++] 时,您不会打印相同的值,因为索引的第二次会增加。

此外,count 将增加两次,因此 array 中的所有其他值都将未初始化。

如果要打印刚刚存储在数组中的值,请使用count-1 作为索引:

while(token=strtok(NULL,";,")){
    number = atoi(token);
    array[count++] = number;
    printf("%d",array[count-1]);
} 

【讨论】:

  • 如果我在分配array[count++] 后打印array[count],同样的问题仍然存在
【解决方案2】:

printf 语句正在使用一个 'count' 值,该值已经超过数组中放置该值的位置。

下面这对行更糟糕,因为

1) 计数增加超过放置值的位置 2) 在 printf 语句中计数再次递增

array[count++] = number;
printf("%d",array[count++]);

建议在循环结束时只增加一次计数

应检查 fopen 的返回值是否为 != NULL 以确保操作成功,如果不成功,则调用 perror() 然后 exit()

这个循环:

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++]);
   } 

}

有几个问题,建议:

while(fgets (string, LMAX, fp)) 
{ 
   //Reading/echoing the file, line by line
   printf("%s", string);

   token = strtok(string,",");

   while(token)
   {
       number = atoi(token);
       array[count] = number;
       printf("%d",array[count++]);
       token =strtok(NULL,";,"));
   } 
}

即使是这些更改,仍然需要检查 array[] 是否被完整添加。

【讨论】:

    猜你喜欢
    • 2015-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多