0

I need some help understanding what's going on. I wrote a program that works with all specified inputs in CS50 IDE, but Check50 gives an error for one of the inputs:

:( outputs "RTB" for " robert thomas bowden" \ expected output, but not "RTB\u0000\n"

Looks like it prints the null character at the end of the string, but I don't see why. I can get it to pass Check50 by removing "+1" from "name[i+1]" in either of the loops, but I don't understand why it works then and not now. I want to find the error in my reasoning. Here's my code:

#include <stdio.h>
#include <cs50.h>


void printInitials();

int main (void)
{
    printInitials();
}

void printInitials() 
{
    string name = get_string();
    if (name != NULL)
    {
        //iterate over the characters in the name string
        for (int i = 0; name[i+1] != '\0'; i++)
        {
            //if the current char is space, immediately go to next iteration
            if (name[i] == ' ')
            {
                continue;
            }
            else
            //if the current char is not space, check to see if it's uppercase. 
            //If it isn't, capitalize it. 
            {
                if (name[i] >= 97 && name[i] <= 122)
                {
                    name[i] -= 32;
                }
                //print the character
                printf("%c", name[i]);

                //move to the next space in the string, or to its end
                while ((name[i] != ' ') && (name[i+1] != '\0'))
                {
                    i++;
                }
            }
        }
        printf("\n");
    }
}

In the code as I wrote it here, when name[i+1] != '\0' condition in the while loop evaluates to false that exact same condition should also evaluate to false in the for loop, and no more printing of any kind should be happening (I would think), but yet it does.

1 Answer 1

1

for (int i = 0; name[i+1] != '\0'; i++) is a bad idea, especially with that inner loop. The other case where that is bad is if you input an empty string, which the used get_string function luckily does not return (it returns NULL then).

What happens in your function is, the inner while loop will place i just before '\0' (name[i+1]=='\0'), then i is incremented as part of the outer loop (now name[i]=='\0'), and you next check the element i+1, right after the zero.

1
  • Thanks! I thought, erroneously, that if condition in the for loop evaluates to false then i++ won't be executed. Turns out it is - everything in the parenthesis is. I'm new to programming, so yeah. Live and learn. I fixed my program by substituting outer for loop with a while loop. Jan 23, 2017 at 22:18

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .