0

This my code for the pset problem Initials and it works correctly.

/*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*/

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

int main(int argc, string argv[])
{
   for(int i = 0; i < argc; i++)
   {
       int j, n;

       //prints initials in capital letters
       for(j = 0, n = strlen(argv[i]); j < n; j++)
       printf("%c", toupper((char) argv[j][0]));
   }
   printf("\n");
}

it compiles the initials,but its always followed by a segmentation fault.

~/workspace/pset2/ $ make initial1
clang -ggdb3 -O0 -std=c11 -Wall -Werror -Wshadow    initial1.c  -lcs50 -lm -o initial1
~/workspace/pset2/ $ ./initial1 olarinde ayodeji
.OASegmentation fault
~/workspace/pset2/ $ 

Any reason for the segmentation fault?

1 Answer 1

1

You can avoid segfault by removing the second for function and replacing the j in the printf with an i. It should look like this:

   for(int i = 0; i < argc; i++)
   {
       printf("%c", toupper((char) argv[i][0]));
   }
   printf("\n");

Still, this code doesn't do what the comment at the beginning of your code says (and I assume that's what the requirement of the problem set is). It should ask the user for his/her name and print the initials in uppercase. Instead it prints the first character in uppercase of every word (delimited by space) of the command you use to execute the code.

So if you execute it by typing ./initial1 asd bdf it will print out .AB
Instead you should be able to execute it with ./initial1, then it should ask you for your name, then you should be able to write your name, and after you do that it should print your initials in uppercase.

1
  • i got it to print the first initial but the second is printing #include <stdio.h> #include <cs50.h> #include <ctype.h> #include <string.h> int main(int argc, string argv[]) { int i = 0; { //prints initials in capital letters printf("Your Name: \n"); string N = GetString(); argv[i] = N; printf("%c", toupper((char) argv[i][0])); } printf("\n"); }
    – Jere
    Commented Sep 9, 2016 at 6:45

You must log in to answer this question.

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