我必须读取一个文件并使用链表将数据存储在C中



我必须读取一个文件并使用链表来存储数据。文件如下所示:

9 92 38 2 magenta 0
54 117 7 46 red 0
129 15 29 49 cyan 0
165 143 33 47 magenta 0

所以我的结构是这样的:

struct rect
{ 
int x;
int y; 
int w;
int h;
char c[7];
int fill;
int ID;
int area;
struct rect* next;
};
typedef struct rect rect_t;
rect_t *head;

我的程序运行良好,目前正在存储数据,但在最后一部分,我必须打印颜色和存在的每种颜色的id所以我的输出应该是这样的:

red: 1
green:
blue:
yellow:
cyan: 2
magenta: 0 , 3
black:

.txt文件的每一行都是ID号。

对于颜色,我有一个枚举器:

enum Colors {red,green,blue,yellow,cyan,magenta,black};

我用这个函数来获取它的颜色:

char* sColorNames(int iColorNumber){
switch(iColorNumber){
case red:
return "red";
break;
case green:
return "green";
break;
case blue:
return "blue";
break;
case yellow:
return "yellow";
break;
case cyan:
return "cyan";
break;
case magenta:
return "magenta";
break;
case black:
return "black";
break;
}
}

我这部分的代码是这样的:

void PrintColorsID(int n){
rect_t *current;
current = head;
int cnt2,cnt1,counter;
for(cnt1 = red; cnt1 < black + 1; cnt1++){
printf("%s:",sColorNames(cnt1));
for(cnt2; cnt2 < n; cnt2++){
if(strcmp(current->c,sColorNames(cnt1)) == 0){
counter++;
}
}
for(cnt2; cnt2 < n; cnt2++){
if(strcmp(current->c,sColorNames(cnt1)) == 0 && counter > 1){
printf(" %d",current->ID);
}
else if(strcmp(current->c,sColorNames(cnt1)) == 0 && counter == 1){
printf(" %d",current->ID);
break;
}
}
putchar('n');
}       
}

通过这样做,我得到的结果是:

red: 
green:
blue:
yellow:
cyan: 
magenta: 
black:

我还尝试了一个while循环:

void PrintColorsID(int n){
rect_t* current;
current = head;
int cnt1,cnt2,counter;
while(current!=NULL){
for(cnt1 = red; cnt1 < black + 1; cnt1++){
printf("%s:",sColorNames(cnt1));
for(cnt2 = 0; cnt2 < n; cnt2++){
if(strcmp(current->c,sColorNames(cnt1)) == 0){
counter++;
}
}
if(strcmp(current->c,sColorNames(cnt1)) == 0 && counter > 1){
printf(" %d",current->ID);
counter--;  
}
else if (strcmp(current->c,sColorNames(cnt1)) == 0 && counter == 1){
printf(" %d",current->ID);
break;
}
printf("n");
}
current = current->next;
}
}

但我得到的输出是:

red:
green:
blue:
yellow:
cyan:
magenta: 0
black:
red: 1
green:
blue:
yellow:
cyan:
magenta:
black:
red:
green:
blue:
yellow:
cyan: 2
magenta:
black:
red:
green:
blue:
yellow:
cyan:
magenta: 3
black:

有谁能告诉我这是怎么回事吗?我想不出别的办法了。

我相信在您的代码中,您正试图循环浏览现有的颜色枚举列表,并检查列表中是否有条目,并打印名称和ID。

我相信,你不必有";计数器";实施和";cnt2";环

与您共享while的代码(第一个代码似乎不正确或是编译版本(。

此外,在您的代码中,您没有为endof字符串char放置enoguh空间。因此,strcmp函数可能会失败。

void PrintColorsID(int n){
rect_t* current;
current = head;
int cnt1 = 0;
int isfirst = 1;
for(cnt1 = red; cnt1 < black; cnt1++){
printf("%s:",sColorNames(cnt1));
current = head;
isfirst = 1;
while(current!=NULL){                         
if(strncmp(current->c,sColorNames(cnt1),7) == 0){
if (isfirst) {
isfirst = 0;
} else {
printf(",");
}
printf(" %d",current->ID);                           
}

current = current->next;
}     
printf("n");           
}
}

最新更新