我是C和编程的新手。我被困在一项家庭作业中。我的输出仅以大写形式显示第一个字符,并以一些奇怪的数字显示其后的字符。有人可以看看我的代码,并给我一些有关我做错了什么以及解决问题的方法的提示吗?非常感谢您的帮助!
“写一个函数void sticky(char * 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;
}
最佳答案
您需要使用strlen
而不是sizeof
来查找char *字符串的长度
关于c - C语言中的指针和数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15648531/