I finished PSet2 with all the correct results, but I'm trying to figure out why I had to change some of my code in initials.c to make it work properly. The original code is as follows:
#include <stdio.h>
#include <cs50.h>
#include <string.h>
// Prestage functions
string GetInit(string fName);
string MakeCap(string inits);
int main(void)
{
// printf("This program will convert your name to initials.\n");
// printf("Please input your name: ");
string name = GetString();
string initials = GetInit(name);
initials = MakeCap(initials);
printf("%s\n", initials);
}
string GetInit(string fName)
{
int spaces = 0;
// Count spaces in the input for array size
for (int count = 0; count < strlen(fName); count++)
{
if (fName[count] == ' ')
{
spaces++;
}
}
// Leave space for first and terminating characters
char inits[spaces + 2];
// Set first initial to assumed first character
inits[0] = fName[0];
// Increment position counter for next position
int initPos = 1;
// Find other letters
for (int count = 0; count <= strlen(fName); count++)
{
// Find space and add next character
if (fName[count] == ' ')
{
inits[initPos] = fName[count + 1];
initPos++;
}
}
// Add terminating character to the end
inits[spaces + 1] = '\0';
// Convert to string
string initials = inits;
// Pass to make captial
return initials;
}
string MakeCap(string inits)
{
for (int count = 0; count <= strlen(inits); count++)
{
// Find lowercase and convert to uppercase
if (inits[count] > 'Z')
{
inits[count] -= 'a' - 'A';
}
}
return inits;
}
I used the gdb debugger to follow along with the code. On line 15 (initials = MakeCap(initials);), the value of initials becomes the capitalized initials as expected. On line 16 (printf), however, initials becomes a garbled mess and the output becomes strange characters.
Now, what's truly baffling is that if I remove the comments from the first two printf's on top, this bug does not occur. Also, if I call GetInit(name) but move the rest of the code into the GetInit function, the bug does not occur.
Why do you think the initials variable would change contents after using printf, and why would it be fine if I use a printf function in the beginning or move the last printf into a different function?