我有一个动态分配的2D线阵列,如下所示:
2152,1,MAIN,AAST,2337,1,26873,LEC - Lecture,5,5,0,0,0,Ronnie W Liggett,liggett@uta.edu,COBA,348,9:00 AM,9:50 AM,Y,N,Y,N,Y,N,N,1/20/2015,5/8/2015
2152,1,MAIN,AAST,4391,1,26881,IND - Independent Study,1,5,4,0,0,Schnavia S Hatcher,shatcher@uta.edu,,,,,N,N,N,N,N,N,N,1/20/2015,5/8/2015
2152,1,MAIN,AAST,3339,1,29501,LEC - Lecture,5,5,0,0,0,Krystal K Beamon,kbeamon@uta.edu,UH,104,11:00 AM,12:20 PM,N,Y,N,Y,N,N,N,1/20/2015,5/8/2015
2152,1,MAIN,ACCT,3309,6,27298,LEC - Lecture,59,59,0,0,0,Terra C Mcghee,tcbrown@uta.edu,COBA,256,9:00 AM,11:50 AM,N,N,N,N,Y,N,N,1/20/2015,5/8/2015
所有1000行按其主题按字母顺序进行气泡排序(在上例中为第四列,AAST和ACCT)。我需要打印每个主题的总注册数,即第9列(本例中为5,1,5,59)。我的代码如下:
for(i=0;i<count;i++)
{
total = 0;
strcpy(currentLine, addresses[i]);
currentSubject = getSubject(currentLine);
for(i;i<count;i++)
{
printf("%d\n", i);
strcpy(nextLine, addresses[i]);
nextSubject = getSubject(nextLine);
if(strcmp(currentSubject, nextSubject) == 0)
{
strcpy(nextLine, addresses[i]);
enrollment = getEnrollment(nextLine);
total += enrollment;
}
else
{
printf("%s %d\n", currentSubject, total);
break;
}
}
}
其中:
我一直使用strcpy()来避免因strok()而损坏原始字符串。但是,这个逻辑似乎不起作用,因为我的总计显示为:
AAST 11
ACCT 193
ADVT 12
相关的行(我删除了所有无用的信息,因此更容易阅读)是:
AAST,5
AAST,1
AAST,5
ACCT,59
ACCT,26
ACCT,34
ACCT,37
ACCT,18
ACCT,59
ACCT,19
ADVT,136
ADVT,12
对于ACCT来说,倒数第二个值(59)没有被添加,而对于ADVT,倒数第二个值(136)也没有被添加。我的逻辑出了什么问题?
答案 0 :(得分:1)
对嵌套循环使用相同的索引i
。你不应该在外循环中增加它,你应该将printf
移出内循环以避免错过最后的条目。
试试这个:
for (i = 0; i < count;) {
total = 0;
strcpy(currentLine, addresses[i]);
currentSubject = getSubject(currentLine);
for (; i < count; i++) {
strcpy(nextLine, addresses[i]);
nextSubject = getSubject(nextLine);
if (strcmp(currentSubject, nextSubject) != 0)
break;
strcpy(nextLine, addresses[i]);
total += getEnrollment(nextLine);
}
printf("%s %d\n", currentSubject, total);
}