2013-03-10 68 views
0

我正在用字符串在C中锻炼,我不得不点一些文字。字母顺序一个二维数组

#include <stdio.h> 
#include <string.h> 

main(){ 
     int cch=0, cw=0, i, j, w=0, ord=0, f=0; //counter and index 
     char testo[80]; 
     char alfa[50][25]; 
     char swap[25]; 

     printf("Write the test:\n"); 
     gets(testo); 

     if(testo[0]!='\0'){ 
       cw=1; 
       for(i=0;testo[i]!='\0';i++){ 
         cch++; 
         if(testo[i]==' '){ 
           cw++; 
         } 
       } 
     } 

     for(i=0;i<cch;i++){ 
       if(testo[i]==' ' && testo[i+1]==' '){ 
         cw--; 
       } 
     } 

     if(testo[0]==' '){ 
       cw--; 
       w--; 
     } 

     printf("\nIn the test there are %d characters\n", cch); 
     printf("In the test there are %d words\n", cw); 

     if(cw>0){ 
       printf("\nUsed words:\n"); 
       for(j=0;j<cch;j++){ 
         if(testo[j]==' ' && testo[j+1]==' '){ 
           //nothing to do  
         } 
         else{ 
           if(testo[j]!=' '){ 
             alfa[w][f]=testo[j]; 
             f++; 
           } 
           else if(testo[j]=='\0'){ 
             alfa[w][f]='\0'; 
             f=0; 
             w=0; 
           } 
           else{ 
             alfa[w][f]='\0'; 
             w++; 
             f=0; 
           } 
         } 
       } 

       for(i=0;i<cw;i++){ 
         printf("%d> %s\n", i+1, &alfa[i]); 
       } 

       //order 
       f=1; 
       printf("\nWord used in alphabetical order:\n"); 
       while(f==1){ 
         f=0; 
         for(i=0;i<cw-1;i++){ 
           ord=strcmp(alfa[i],alfa[i+1]); 
           if(ord>-1){ 
             strcpy(swap,alfa[i]); 
             strcpy(alfa[i],alfa[i+1]); 
             strcpy(alfa[i+1],swap); 
             f=1; 
           }  
         } 
       } 

       for(i=0;i<cw;i++){ 
         printf("%d> %s\n", i+1, alfa[i]); 
       } 
     } 
     else{ 
       printf("You haven't written any word.\n"); 
     } 
} 

的问题是,如果有两个相同的话,而这句话是超过2个,我有一个循环,我没有任何结果,我该怎么办? 在OpenVMS上测试。 谢谢。 PS:我知道现在有很多bug,但是我有问题要解决这个问题。

回答

4
if(ord>-1){ 
    /* ... */ 
} 

如果两个词是相同的strcmp将返回0。这将交换两个词,直到你的下一个电力帐单进来,你关闭你的程序。取而代之的是,检查结果是否大于零:

if(ord > 0){ 
    /* ... */ 
} 

参见:strcmp

+0

谢谢:)那个愚蠢的错误,我做了 – Mitro 2013-03-10 08:50:38

+1

@AlessioMTX:发生在每个人。进一步的评论:'strtok'会让你的字数更容易计算,并且可以和'strlen'一起使用。 – Zeta 2013-03-10 08:51:49

+0

感谢您的建议;) – Mitro 2013-03-10 08:53:02