C编程:反向排序列表

时间:2017-04-03 22:35:59

标签: c sorting for-loop

我正在尝试“滚动”一个名单列表,我向右下方向下滚动,但我无法弄清楚如何向后滚动(向上滚动)。我的错误在于i + j -1,但我不能在没有分段错误的情况下获得正确的输出。这是因为我试图访问我假设的负数。

int i,list,j = 1;
char answer [5];
 do {
     if (strcmp(answer, "+") == 0) {
         printf("Number of Contacts = %d\n", count);
         for(i=1;i<6;i++) {
             if ((i + j) - 1 == count) {
                 printf("end of list\n");
                 break;
             } else {
                 list = i + j;
                 if(strcmp(contactData[(i+j)-1].company_name," ") == 0) {
                     printf("%d.\t%s %s\n", list, contactData[(i+j)-1].first_name, contactData[(i+j)-1].last_name);
                 } else {
                     printf("%d.\t%s\n", list, contactData[(i+j)-1].company_name);
                 }
             }
          }
      }

     if (strcmp(answer, "-") == 0) {
         printf("Number of Contacts = %d\n", count);
         for(i=1;i<6;i++) {
             if ((i + j - 1) < 0) {
                 printf("end of list\n");
                 break;
             } else {
                 list = j - i;
                 if(strcmp(contactData[(j-i)-1].company_name," ") == 0) {
                     printf("%d.\t%s %s\n", list, contactData[(j-i)-1].first_name, contactData[(j-i)-1].last_name);
                 } else {
                     printf("%d.\t%s\n", list, contactData[(j-i)-1].company_name);
                 }
             }
          }
      }

      printf("Action(+,-,#,A,X):");
      scanf("%s", answer);
      getchar();
      j++;

  } while (1)

这是我的输出:

Number of Contacts = 14
1.      Chiraq
2.      Cobra
3.      Andre D'Souza
4.      Gucci
5.        Jordan
Action(+,-,#,A,X):+
Number of Contacts = 14
2.      Cobra
3.      Andre D'Souza
4.      Gucci
5.        Jordan
6.      Migos
Action(+,-,#,A,X):+
Number of Contacts = 14
3.      Andre D'Souza
4.      Gucci
5.        Jordan
6.      Migos
7.      North Face

1 个答案:

答案 0 :(得分:0)

如果您的contactData数组从[0]开始,到[count-1]结束,则此示例可能适合您。

int i,list,j = 0;
char answer [5];
do {
    printf("Number of Contacts = %d\n", count);
    for(i=0;i<6;i++) {
        list = i+j;
        if (list >= count) {
            printf("end of list\n");
            break;
        }
        if(strcmp(contactData[list].company_name," ") == 0) {
            printf("%d.\t%s %s\n", list+1, contactData[(list].first_name, contactData[list].last_name);
        } else {
            printf("%d.\t%s\n", list+1, contactData[(list].company_name);
        }
    }

    printf("Action(+,-,#,A,X):");
    scanf("%s", answer);
    if(strcmp(answer, "+") == 0) {
      if((j+1)<count) j++;
    }
    else if(strcmp(answer, "-") == 0) {
      if(j>0) j--;
    }
} while (1);