Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer and Array in C

Tags:

arrays

c

pointers

I'm new to C and programming. I got stuck at a homework exercise. My output only shows the first character in upper case, and the following characters in some weird numbers. Can someone take a look at my code and give me some tips on what I've done wrong and ways to fix the issue? Your help is greatly appreciated!

"Write a function void sticky(char* word) where word is a single word such as “sticky” or “RANDOM”. sticky() should modify the word to appear with “sticky caps” (http://en.wikipedia.org/wiki/StudlyCaps), that is, the letters must be in alternating cases(upper and lower), starting with upper case for the first letter. For example, “sticky” becomes “StIcKy” and “RANDOM” becomes “RaNdOm”. Watch out for the end of the string, which is denoted by ‘\0’. You can assume that legal strings are given to the sticky() function."

#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;

}

like image 234
user2203774 Avatar asked Jul 17 '26 17:07

user2203774


1 Answers

you need to use strlen not sizeof to find the length of a char* string

like image 145
Keith Nicholas Avatar answered Jul 20 '26 09:07

Keith Nicholas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!