从文本文件读取到字符串数组

时间:2016-01-09 09:15:07

标签: c arrays text

我在将文本文件中的字符串读入数组时遇到了困难。鉴于文本文件:

7
{5, 2, 3}, {1,5}, { }, { }, {3}, { }, { }

我正在尝试使用fscanf将第二行传递到一维数组 排除{},。 产量:

array[0] = 523
array[1] = 15
array[2] = null or 0

...

到目前为止,这是我的代码:

 #include <stdio.h>
 #include <stdlib.h>

 int main()
 {
int i=0,numberofvertexes;
int *aq;
int *ad;
char str1[20];

printf("Please enter a name of an input file:\n>>");

gets (str1);

FILE *file = fopen(str1,"r");

fscanf(file ,"%d", &numberofvertexes);

printf("Number of Vertexes: %d",numberofvertexes);

aq = (char*)calloc(numberofvertexes, sizeof(char));

while(!feof(file))
{
    fscanf(infile,"%s",&aq[i]);
    i++;
}


ad = (int*)calloc(numberofvertexes,sizeof(int));

1 个答案:

答案 0 :(得分:1)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void){
    FILE *fp = fopen("data.txt", "r");

    int size;
    fscanf(fp, "%d", &size);

    int *array = calloc(size, sizeof(*array));
    char buff[1024];
    int i = 0, n;
    while(1==fscanf(fp, " {%1023[^}]} ,", buff)){//read { ... },
        if(i == size){
            fprintf(stderr, "many data\n");
            break;
        }
        const char *sep = ",";
        char *num = strtok(buff, sep);//separate by ","
        while(num){
            array[i] = array[i] * 10 + atoi(num);//Synthesis
            num = strtok(NULL, sep);
        }
        ++i;
    }
    fclose(fp);
    n = i;
    for(i = 0; i < n; ++i)
        printf("array[%d] = %d\n", i, array[i]);

    free(array);
    return 0;
}