簡體   English   中英

將評論讀入動態大小的數組

[英]Reading comments into an array of dynamic size

所以我在標記文件中有一系列評論:

# comment1
# comment2

我想將它們讀入數組以添加到我的結構中的注釋數組中。 我事先不知道評論行的數量

我在結構中聲明注釋數組,如下所示:

char *comments; //comment array

然后我開始閱讀其中的評論,但是我沒有用:

int c;
//check for comments
c = getc(fd);
while(c == '#') {
    while(getc(fd) != '\n') ;
    c = getc(fd);
}
ungetc(c, fd);
//end comments?

我什至靠近嗎?

謝謝

第一

char *comments; //comment array

是一個評論而不是評論數組。

您需要使用realloc來創建字符串數組

char**comments = NULL;
int count = 10; // initial size
comments  = realloc(comments, count);

當你>計數

count*=2;
comments = realloc(comments, count);// classic doubling strategy

將字符串放入數組(假設注釋是一個char *,其中有一個注釋

   comments[i] = strdup(comment);

您可以使用形式為<stdio> fgets()一次讀取一行。

int num_comments = 0;
char comment_tmp[82];
char comment_arr[150][82];
while(comment_tmp[0] != '#' && !feof(file_pointer)){
    fgets(comment_tmp, 82, file_pointer);
    strcpy(comment_arr[num_comments], comment_tmp);
    num_comments++;
}

這具有只能存儲150條注釋的限制。 可以通過以下方法克服這一問題:1)在此設置一個更大的數字,2)使用動態內存分配(認為是malloc / free),或3)將您的注釋組織為更靈活的數據結構(如鏈表)。

當您看到該行是注釋時,將注釋的值存儲在注釋變量中,只需轉到下一行並再次執行此循環即可。 所以代碼:

char c = getc(fd);
while(c == '#') {
    while(getc(fd) != '\n') /* remove ; */ {
    *comment = getc(fd);
    ++comment;
    }
}

或使用更簡單的fscanf

fscanf(fd,"#%s\n",comment); /* fd is the file */

請注意,這里的注釋是一個字符串,而不是字符串數組。

對於字符串數組,它將是:

#define COMMENT_LEN 256

char comment [COMMENT_LEN ][100];
int i = 0;
while(!feof(fd) || i < 100) {
     fscanf(fd,"#%s\n",comment[i]);
     getch(); /* To just skip the new line char */
     ++i;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM