-1

我有一个文本文件,每一行都包含逗号分隔值的人名和性别。我正在尝试逐行阅读并创建人员数组。不确定我的代码出了什么问题,数组的所有元素都设置为文本文件的最后一行。(如果最后一行有Sam,Male,则person数组的所有元素都设置为Name=Sam)

  struct Person{
      char* Name;
      char* Gender;
  };
  struct Person person[100];

  void readAllFromFile(){
       FILE * fp;
       char currentLine[256];
       int fd;
       if((fp = fopen ("test.txt", "r"))==NULL){
           perror("Can not open");
          fclose(fp);
          return;
       }
       int currentLineNo=0;
       char *items;
       while (fgets(currentLine, sizeof(currentLine), fp)) {
           items=strtok(currentLine,",");
           struct Person tempPerson;
           int iter=0;
           while(items != NULL)
           {
              if(iter==0){
                  tempPerson.Name=items;
              }
               else {
                  tempPerson.Gender=items;
              }
             iter++;
             items=strtok(NULL,",");
          }
          person[currentLineNo]=tempPerson;
          currentLineNo++;
       }

       /*Printing element of the array*/
       int i;
       for(i=0;i<currentLineNo;i++){
       printf("%s\n",person[i].Name);
     }
    fclose(fp);
   }

  int main() {
     readAllFromFile();
     return 0;
  }
4

1 回答 1

1

每个人的名字都在记忆中的同一个地方:currentLine. 您将该地址分配给每个Persons Name,因此每个名称都将显示相同。每个 类似的东西Gender

请注意,由于currentLine是本地的readAllFromFile,一旦该函数返回,该空间可能会用于其他事情,从而破坏Name您设法保留的空间。

每个都Person需要为自己的Name和分配空间Gender

于 2017-09-16T00:24:38.723 回答