2016-04-10 30 views
-1

如标题所示,是否可以将字符串数组中的元素添加到结构数组中?例如,我有我的以下代码:将数组中的元素添加到结构数组中

#include<string.h> 
#include<stdio.h> 
#include<stdlib.h> 
#define MAX_SIZE 500 

typedef struct User 
{ 
    char fullName[MAX_SIZE]; 
    char description[MAX_SIZE]; 
    char userName[MAX_SIZE]; 
    char password[MAX_SIZE]; 
} userData[MAX_SIZE]; 

int main (void) 
{ 
    int j=0; 
    int numData=0; 
    char* data[500]; 
    char line[500]; 
    int i=0; 
    userData newUser; 
    FILE *file; 
    file = fopen("users.txt", "r"); 
    while(fgets(line, sizeof(line), file)) 
    { 
     data[i]=strdup(line); 
     i++; 
     numData++; 
    } 
    for (j=0 ; j<numData+1; j++) { 
     printf("%s", data[j]); 
    } 

    fclose(file); 

    return 0; 
} 

此刻此代码的作用是将我的users.txt文件中的行添加到字符串数组中。我想现在做的是从该字符串数组中的元素添加到我的结构阵列,例如是这样的:

NEWUSER [1] .fullName =第一字符串数组

NEWUSER [的元件1] .DESCRIPTION =字符串数组

的第二元件...

这将是可能的?或者有没有一种方法可以将文件中的行添加到我在上面解释的格式中的结构数组中,而无需使用字符串数组?

任何帮助表示赞赏!

+0

缩进你的代码。 – gsamaras

+0

我知道我并不是唯一对程序来自哪里的人好奇。我很确定'#include '也会呕吐。请*,请*,发布*真实*代码。 – WhozCraig

+0

不,你不是@WhozCraig。我也很好奇,为什么你必须缩进他的代码,这不会那么困难。 – gsamaras

回答

0

阅读完该行后,可以使用sscanf函数填充结构数组的第i个元素。你不需要再使用字符串数组。您可以在sscanf中指定您的字符串格式,并填写第i个新用户的所有字段。