2015-10-23 44 views
1

該程序應該將句子轉換一定的量。 如果我有一個3的轉變,那麼字母a應該是d。但是,當我將字符串傳遞給我的移位功能時,它不會移動我的任何值。C程序將file-io傳遞到函數

#include <stdio.h> 

#define MAX_LEN 100 

void decode(char *sentence, int shift); 

int main(void) 
{ 
    FILE *ifp; 
    FILE *ofp; 

    char str[MAX_LEN]; 
    int shift_by = 0; 

    scanf("%d", &shift_by); 

    ifp = fopen("input.txt", "r"); 
    ofp = fopen("output.txt", "w"); 

    if (ifp == NULL) { 
     printf("FILE doesnt open"); 
     return 1; 
    } 

    while(fgets(str, MAX_LEN, ifp) != NULL) { 
     shift(str, shift_by); 
     fprintf(ofp," %s", str); 
    } 

    fclose(ifp); 
    fclose(ofp); 
    return 0; 
} 

void decode(char *sentence, int shift) 
{ 
    char *p; 
    p = sentence; 

    if ((*p >= 'a') && (*p <= 'z')) { 
     *p = (*p - 'a') + shift % 26 + 'a'; 
    } 

    if ((*p >= 'A') && (*p <= 'Z')) { 
     *p = (*p - 'A' + shift) % 26 + 'A'; 
    } 

} 
+0

不應該shift_by不是0?它打印,但沒有轉移? –

+0

如何定義「shift」功能? – MikeCAT

+0

與以下表達式相比,表達式* * =(* p - 'a')+ shift%26 +'a';'看起來很奇怪。它不應該是'* p =(* p - 'a'+ shift)%26 +'a';'? – MikeCAT

回答

1

請嘗試下面的代碼它的作品。你認爲'解碼',但你輸入'移位'。我簡化了代碼。現在你可以嘗試使它與指針一起工作。 玩得開心。

#include <stdio.h> 

#define MAX_LEN 100 

void decode(char *sentence, int shift); 

int main(void) 
{ 
    FILE *ifp; 
    FILE *ofp; 

    char str[MAX_LEN]; 
    int shift_by = 0; 

    printf("\nPlease enter shift by and press enter\n"); 
    scanf(" %d", &shift_by); 

    ifp = fopen("input.txt", "r"); 
    ofp = fopen("output.txt", "w"); 

    if (ifp == NULL) 
    { 
    printf("FILE doesnt open"); 
    return 1; 
    } 

    while (fgets(str, MAX_LEN, ifp) != NULL) 
    { 
    decode(str, shift_by); 
    fprintf(ofp, " %s", str); 
    } 

    fclose(ifp); 
    fclose(ofp); 
    return 0; 
} 

void decode(char *sentence, int shift) 
{ 
    int i = 0; 
    char p; 

    while (p = sentence[i]) 
    { 
    if ((p >= 'a') && (p <= 'z')) 
    { 
     p = (p - 'a') + shift % 26 + 'a'; 
    } 

    if ((p >= 'A') && (p <= 'Z')) 
    { 
     p = (p - 'A' + shift) % 26 + 'A'; 
    } 

    sentence[i] = p; 
    i++; 
    } 

}