Originally Posted by
c99tutorial
Code:
char message[25];
printf("What is your message to the world?\n");
fgets(message, sizeof(message), stdin);
message[sizeof(message)-1] = '\0'; // Ensure '\0' termination.
You've accidentaly used sizeof instead of strlen in removing the newline. Should be:
Code:
message[strlen(message)-1] = '\0'; // Ensure '\0' termination.
There are, of course, some problems with this approach, but it's good enough for now.
As for the loop in the code, it could be written like this:
Code:
for(int i = 0, n = strlen(message); i < n; i++)
printf("%c", toupper(message[i]));
toupper passes a character through unchanged if it can't be converted to upper case.
You can avoid the strlen call, too:
Code:
for(int i = 0; message[i] != '\0'; i++)
printf("%c", toupper(message[i]));
And you should print a final newline afterwards since if you don't the prompt appears on the same line as the output (on linux, at least).
Now that I think about it, there's no reason to use the expensive printf function when the cheap putchar will do:
Code:
for(int i = 0; message[i] != '\0'; i++)
putchar(toupper(message[i]));
putchar('\n');
Defintion of the day:
abactor: one who steals cattle