【发布时间】:2013-03-26 22:23:10
【问题描述】:
我是 C 和编程新手。我被困在家庭作业中。我的输出仅显示大写的第一个字符,以及一些奇怪数字的以下字符。有人可以看看我的代码并就我做错了什么以及解决问题的方法给我一些提示吗?非常感谢您的帮助!
"编写一个函数 void sticky(char* word) ,其中 word 是单个单词,例如“sticky”或“RANDOM”。sticky() 应该修改单词以显示为“sticky caps” (http://en.wikipedia.org/wiki/StudlyCaps),也就是说,字母必须是大小写交替的(大写和小写),第一个字母从大写开始。例如,“sticky”变成“StIcKy”,“RANDOM”变成“RaNdOm”。注意结尾字符串,用 '\0' 表示。你可以假设给 sticky() 函数提供了合法的字符串。"
#include <stdio.h>
#include <stdlib.h>
/*converts ch to upper case, assuming it is in lower case currently*/
char toUpperCase(char ch)
{
return ch-'a'+'A';
}
/*converts ch to lower case, assuming it is in upper case currently*/
char toLowerCase(char ch)
{
return ch-'A'+'a';
}
void sticky(char* word){
/*Convert to sticky caps*/
for (int i = 0; i < sizeof(word); i++)
{
if (i % 2 == 0)
{
word[i] = toUpperCase(word[i]);
}
else
{
word[i] = toLowerCase(word[i]);
}
}
}
int main(){
/*Read word from the keyboard using scanf*/
char word[256];
char *input;
input = word;
printf("Please enter a word:\n");
scanf("%s", input);
/*Call sticky*/
sticky(input);
/*Print the new word*/
printf("%s", input);
for (int i = 0; i < sizeof(input); i++)
{
if (input[i] == '\n')
{
input[i] = '\0';
break;
}
}
return 0;
}
【问题讨论】:
-
/*converts ch to lower case, assuming it is in upper case currently*/反之亦然是个大线索。 -
融合 Keith 的答案和 ritesh 的似乎最好