C 将注释读入动态大小的数组
因此,我在标记文件中有一系列注释:C 将注释读入动态大小的数组,c,arrays,C,Arrays,因此,我在标记文件中有一系列注释: # comment1 # comment2 我想将它们读入一个数组,以便添加到我的结构中的注释数组中我事先不知道评论行的数量 我在我的结构中声明注释数组,如下所示: char *comments; //comment array 然后我开始阅读中的评论,但我得到的不起作用: int c; //check for comments c = getc(fd); while(c == '#') { while(getc(fd) != '\n') ;
# 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
将字符串放入数组(假设comment是一个char*,其中有一条注释
comments[i] = strdup(comment);
您可以使用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;
}
#定义注释#第256页
char comment[comment_LEN][100];
int i=0;
而(!feof(fd)| i<100){
fscanf(fd,“#%s\n”,注释[i]);
getch();/*跳过新行字符*/
++一,;
}
1号。每一个getc
都会立即消耗一个字符,因此在内部循环中会丢失其中的一半。2.单个char*comment
只能存储一个C字符串(当然,除非您想用非0个字符分隔它们)。3.你读了字符,但在某个地方你忘了存储它们。