2014-02-10 48 views
5

所以,我想要做的是創建一個函數,將大寫字母切換爲小寫字母,反之亦然。小寫字母<-->大寫字母不能按計劃工作

這裏是我的工作:

#include <stdio.h> 
#include <stdlib.h> 

int caplowswitch(char string[], char switched[]); 

int main(){ 

    char name[] = "whyisthisnotworking"; 
    char flipped[] = ""; 

    caplowswitch(name, flipped); 


return 0; 
} 

int caplowswitch(char word[], char switched[]){ 

    char *ptrword = word; 
    unsigned short int counter = 0; 

    printf("Your text input is: %s \n", word); 

    while(*ptrword != NULL){ 

    switched[counter] = (*ptrword^0x20); 
    counter++; 
    ptrword++; 

    } 

    printf("Your flipped text is: %s \n", switched); 

    return 1; 
} 

在學習的過程。謝謝你的時間。

+2

而這不起作用...怎麼樣?我們應該猜測問題是什麼?我們在這裏幫助,而不是你的調試器。 –

+0

你放入「*切換*」的字符在哪裏結束? (提示:不在數組中切換/翻轉,因爲這只是一個字符長。) –

回答

2
  1. 你忘了空終止添加到switched。您需要添加

    switched[counter] = '\0'; // add '\0' to the end 
    

    printf("Your flipped text is: %s \n", switched); 
    
  2. 您需要更改while(*ptrword != NULL)while(*ptrword != '\0')

  3. @ooga指出,你最好給flipped分配足夠的空間。因此請將char flipped[] = "";更改爲char flipped[100] = "";

修復這些問題後,它應該按預期工作。查看Ideone上的運行結果。

+0

謝謝。我不能相信我錯過了那個哈哈 – Brandacus

+0

不要忘記其他重要的一點,比如沒有爲''翻轉'分配足夠的內存以及在''\ 0''的地方使用'NULL'的錯誤。 – ooga

+0

@ooga更新。感謝您指出了這一點。 – herohuyongtao

1

您沒有給足夠的空間flipped。通過定義和初始化它:

char flipped[] = ""; 

你只給它一個字符,初始化爲'\0',自定義的這種形式僅分配足夠的空間容納給定的字符串,你已經通過了空字符串。 嘗試

char flipped[100] = ""; 
1

你的代碼有三個錯誤。

POINT1:

決不char flipped[] = "";分配內存這樣。這不是一個正確的程序。

點2:

不要檢查空字符這樣while(*ptrword != NULL)。你應該像while(* ptrword!='\ 0')這樣檢查。

點3:

空終止需要switched。所以while(*ptrword != NULL) { ...} set switched[counter]='\0'

相關問題