0

I can't get the GetString() function to work. It works perfect without having to ask the user for an input after the ./initials is executed. That is, if someone just writes ./initials becky, and I use the i < argc function instead of strlen(s) bit in between, everything works. I get the segmentation fault when I try and add in the GetString() function and pass in the name part. Please help!

initials.c

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

int main(int argc, string argv[])
{
    char* s = GetString();
    for (int i = 0, n = strlen(s); i < n; i++)
    {
        if (i > 0)
        {
            for (int j = 0, n = strlen(argv[i]); j < n; j++)
            {
                if (j == 0)
                {
                    printf("%c\n", toupper(argv[i][j]));
                }
            }
        }
    }
    printf("\n");
}

2 Answers 2

1

Per the specs:

Write, in a file called initials.c, a program that prompts a user for their name (using GetString to obtain their name as a string) and then outputs their initials in uppercase with no spaces or periods, followed by a newline (\n) and nothing more.

Your program shouldn't use the argc and argv variables at all. It should just ask for the user's name using GetString. So your inner for loop should not even exist, as you are not supposed to use the argv array. And actually that's where you get the segfault, as you reassign to n a new integer, the length of each argv's string, with result when the outer for loop is revisited, it loops past the end of argv.

You should see in your terminal exactly that:

jharvard@appliance (~/Dropbox/pset2): ./initials
Zamyla Chan
ZC
jharvard@appliance (~/Dropbox/pset2): ./initials
robert thomas bowden
RTB

See that no command line parameters are used.

If this answers your question please accept it by clicking the gray check-mark to the left, so that it becomes green. You can also vote it up by pressing the up arrow above the check-mark.

0

From looking at the code it looks like you are iterating past the end of the string contents - don't forget that the positions start at 0, not 1, so the last position will be the string length minus 1 - a 5 char string would be in positions 0,1,2,3 & 4, not 1 to 5. Its otherwise know as an off by one error. Check out Robs short on arrays - https://www.youtube.com/watch?v=7mOJN1c1JEo

You must log in to answer this question.

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