fais fais - 2 months ago 8
C Question

toupper function in C with for loop

I don't understand why the following code doesn't work as I wanted it to.

int main()
{
char sentence[] = "this will be capitalised";
int i;

for (i=0; i<strlen(sentence); i++)
{
toupper(sentence[i]);
putchar(sentence[i]);
}

printf("\n\n");

return (0);
}


I end up with this:

this will be capitalised

Program ended with exit code: 0


Thank you

Answer

Replace the line:

   toupper(sentence[i]);

with this one:

   sentence[i] = toupper(sentence[i]);

The problem with your code is that toupper does not do the conversion in place, instead it returns the converted letter as its return value.

If you don't want to modify the string and you are only want to print it in uppercase form, then use WolfieeifloW's solution.

Comments