2014-03-06 144 views
0

我試圖在main()中使用此字符比較函數,而忽略區分大小寫。有沒有辦法從main調用toupper(ch1)和toupper(ch2),這樣如果提出-i(不區分大小寫),我可以重用代碼。如何從main()訪問函數變量

int CharacterCompare(FILE *file1, FILE *file2, char file1name[], char file2name[]) 
{ 
    int ch1, ch2; 
    int differ = 0; 

    do 
    { 

    ch1 = fgetc(file1); 
     ch2 = fgetc(file2); 
     differ++; 

     if (feof(file1) && !feof(file2)) 
     { 
     printf("EOF on %s\n", file1name); 
     return 1;   
     } 
     else if (feof(file2) && !feof(file1)) 
     { 
     printf("EOF on %s\n", file2name); 
     return 1; 
     } 

     if (ch1 != ch2) 
     { 
     printf("files differ: char %d\n", differ); 
     return 1; 
     }  
    } 
    while((!feof(file1)) && (!feof(file2)) && (ch1 == ch2)); 

    printf("files are equal\n"); 

    return 0; 
} 
+0

是否需要區分大小寫需要作爲另一個參數傳遞。 –

+0

爲什麼不能在這個對話中使用CharacterCompare – michaeltang

回答

0

答案很短(也是唯一的):不,您不能訪問在其他函數中本地聲明的變量。

而是將不區分大小寫作爲參數傳遞給函數。

0

一般來說,如果您需要重用代碼,請將其包裝在自己的函數中。

在這種情況下,爲什麼會只調用touppermain

... 

    if (toupper(ch1) != toupper(ch2)) 
    { 
    printf("files differ: char %d\n", differ); 
    return 1; 
    } 
... 
    while((!feof(file1)) && (!feof(file2)) && (toupper(ch1) == toupper(ch2))); 

或包裹的區分大小寫的比較成一個函數:

int caseinvariantcomp(char c1, char c2) { 
    return toupper(c1) - toupper(c2); 
} 

... 

    if (caseinvariantcomp(ch1, ch2)) 
    { 
    printf("files differ: char %d\n", differ); 
    return 1; 
    } 
... 
    while((!feof(file1)) && (!feof(file2)) && (!caseinvariantcomp(ch1, ch2))); 
1

朗的答案(沒有測試過,但你shoukld得到的想法):

int Compare(char ch1, char ch2, int ignorecase) 
{ 
    if (ignorecase) 
    { 
    ch1 = toupper(ch1) ; 
    ch2 = toupper(ch2) ; 
    } 

    return ch1 == ch2 ; 
} 


int CharacterCompare(FILE *file1, FILE *file2, char file1name[], char file2name[], 
         int ignorecase) 
{ 
    int ch1, ch2; 
    int differ = 0; 

    do 
    { 
    ch1 = fgetc(file1); 
     ch2 = fgetc(file2); 
     differ++; 

     if (feof(file1) && !feof(file2)) 
     { 
     printf("EOF on %s\n", file1name); 
     return 1;   
     } 
     else if (feof(file2) && !feof(file1)) 
     { 
     printf("EOF on %s\n", file2name); 
     return 1; 
     } 

     if (Compare(ch1, ch2, ignorecase)) 
     { 
     printf("files differ: char %d\n", differ); 
     return 1; 
     }  
    } 
    while((!feof(file1)) && (!feof(file2)) && (ch1 == ch2)); 

    printf("files are equal\n"); 

    return 0; 
} 

而在主要例如一些例如:

ignorecase = argv[1] == "-i" ; 
int different = CharacterCompare(f2, f2, name1, name2, ignorecase) ; 
+0

Got it!非常感激。 – aguilar