### Capitalizing First Letters in String

Hello! :)

I've recently been tasked with a program with the following details:

3 functions - upperc() ~takes in a lowercase letter and converts it to
uppercase~
lowerc() ~takes in a uppercase letter and converts it to
lowercase~
titleprint() ~prints a string with the first letter of each word
capitalized~

Problem: titleprint() ~Everytime I input a string, the program outputs the
string with the first letter of the first word
'disappeared' and the second letter capitalized

Can someone give me clues on what I'm doing wrong with the code? Help is much appreciated.

Code:

 ``1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677`` ``````#include char upperc(char), lowerc(char); void titleprint(char*); int main() { int c; char n, z[100]; scanf("%d %c", &c, &n); if (c == 0) { printf("%c", upperc(n)); } else if (c == 1) { printf("%c", lowerc(n)); } else titleprint(z); } char upperc(char a) { return (a >= 97 && a <= 122) ? a - 32 : a; } char lowerc(char b) { return (b >= 65 && b <= 90) ? b + 32 : b; } void titleprint(char* d) { int c, i; gets(d); for(i = 0, c = 1; i < strlen(d); i++, c++) { if (d[i] == ' ') { c = 0; printf(" "); continue; } else if ((d[i] >= 65 && d[i] <= 90) || (d[i] >= 97 && d[i] <= 122)) { if (c == 1) { d[i] = upperc(d[i]); } else if (c >= 2) { d[i] = lowerc(d[i]); } } } printf("%s", d); } ``````

Last edited on
I think you're just printing some extra whitespace. Comment out printf(" "); on line 54 and see what you get. BTW, you should prefer fgets to gets.
I would recommend simplifying some of your program's logic. Checking for space, lowercase, or uppercase is not needed in your titleprint function. This is because you check in lowerc and upperc such that non-alphabet characters will be unaffected.
Simplified version:
 ``123456789101112131415`` ``````void titleprint(char* d) { int capitalize, i, length; //char d[300]; //fgets(d, 300, stdin); //this would require removing d as a parameter gets(d); length = strlen(d); capitalize = 1; for(i = 0; i < length; i++) { d[i] = (capitalize == 1) ? upperc(d[i]) : lowerc(d[i]); capitalize = (d[i] == 20) ? 1 : 0; } printf("%s", d); }``````

I second m4ster r0shi's recommendation to use fgets. Especially if this function is accepting a pointer from who knows where.

Edit: I had the realization that each word needed the first letter capitalized.
Last edited on
Case checking is indeed not needed in titleprint, however I think checking for whitespace
is necessary for the program to work correctly when multiple words are entered as input.
Oh, I just realized that he wants the first letter of each word capitalized.
Topic archived. No new replies allowed.