2014-02-10 34 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'

相关问题