【问题标题】:Store an array using strtok使用 strtok 存储数组
【发布时间】:2014-12-25 19:08:38
【问题描述】:
int main (){

FILE *file = fopen ( "C:\\input.txt", "r" );
int i=0, j=0, k=0;

char *result[10][10];   
char line[100];    
char *value;
char *res[100][100];

for(i=0; i<=9; i++){         
    for(j=0;j<=9;j++){
        result[i][j] = NULL;
    }
}

while(fgets(line, sizeof(line), file)){
    char *array=strtok(line,"\n");
    res[0][0]=strdup(array);  

    printf("\n\n\n %s RES \n",res[0][0]);
    array=strtok(array,"\n");
    res[0][1]=strdup(array);

    printf("\n\n\n %s RES \n",res[0][1]);
    array=strtok(line,"\n");
    res[0][2]=strdup(array);
}

我想将一个数组逐行存储在一个 txt 文件中。我的输入文件中有3 行。我希望每一行都存储在一个数组中。我怎样才能做到这一点 ?这始终是存储第一个元素。

我的输入文件:

George    :Math1,History2,Math2
ELizabeth :Math2,Germany1,spanish1
Adam      :Germany1,History2,Math1

【问题讨论】:

  • 这总是存储在 res[][] 中同样细:第一行总是
  • 我想将输入文件中的每一行存储在一个数组中。例如我想 res[0][0] = "George :Math1,History2,Math2" , res[0][1]=ELizabeth :Math2,Germany1,spanish1 和 res[0][2]=Adam :Germany1 ,History2,Math1 @giorgim
  • "\n" 传递给strtok() 到底是什么概念?供您参考:man7.org/linux/man-pages/man3/strtok.3.html
  • 如果我不使用 *res[][] ,strtok @giorgim 会出错
  • 确切的想法是 strtok("\n") ---> 将每一行的标记都插入@alk 我认为用于分割每一行。

标签: c arrays runtime-error strtok


【解决方案1】:

为了将这三行读入数组,为什么不使用像这样简单的东西:

 char res[100][100];
 int i =0;
 while(fgets(line, sizeof(line), file)){
        strcpy(&res[i][0],line);
        printf("%s \n",&res[i][0]);
        i++;
 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多