1

I am trying to write a code that prints initials of a given name? I have been getting error whenever I use '/0' - to initialize the ith character of a given string. I am using it to identify initials of the 2nd word? Any suggestions to detect the 2nd word and print the initial of the 2nd word? Additionally, I am trying to write this code so that it ignores any additional spaces:

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

    int main(void)
    {
          printf ("Enter you Name:");//print name
          string s = get_string(); //get input from user 
          printf("%c", toupper(s[0])); // use placeholder to call the string 

           for (int i=0, n = strlen(s); i < n; i++)
            { 
              if (s[i] == '/0')
               {
                printf("%c", toupper(s[i+1]));  
               }
            }
           printf ("\n");
     }
Aakash
  • 73
  • 8

2 Answers2

0

Try to use ' ' instead of '/0'.

if (s[i] == ' ')

or if you prefer ASCII codes (Space is 0x20 or 32 as decimal):

if (s[i] == 0x20)

your code will work if there is only 1 space between names. To avoid this, the condition should also check the next char. If it's not a space then probably it's a 'letter':

if (s[i] == 0x20 && s[i+1] != 0x20) {...

Note that the for cycle should stop at i < n - 1, otherwise the loop will fail if there are trailing spaces...

José Fonte
  • 4,016
  • 2
  • 16
  • 28
0

I'm not sure what your get_string() function does but this does what you're asking for.

int main(void)
{
      printf ("Enter you Name:");//print name
      char input[100];
      cin.getline(input, sizeof(input));
      string s(input);
      //get input from user 
      printf("%c", toupper(s[0])); // use placeholder to call the string 

      for (int i=0, n = s.length(); i < n; i++)
        {
          if (isspace(s.at(i)))
           {
            printf("%c", toupper(s[i+1]));  
           }
        }
       printf ("\n");
 }
user3660570
  • 337
  • 1
  • 14