nghanima
nghanima

Reputation: 1

Asking a user to input their name and outputting their initials in C

I just wanted to start this off by admitting I'm a complete beginner to coding, and that it's not something that comes intuitively to me.

What I'm trying to do is write a simple program that has the user input their full name, and outputs their initials. The logic I'm trying to follow is that since strings in C are just characters in an array, the characters that should be an initial will come after the '\0' value.

I'm not sure if my problem is a problem of logic or translating that logic into working syntax, so any help would be appreciated.

Here is the code in full:

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

int main (void)
{

printf ("Please insert your name. \n");
string name = get_string();
//printf ("Your name is %s\n", name);
int x = 0;
char c = name [x];
while (c != '\0')
    {
        x++;
    }
    printf ("%c/n", c);

}

I understand it's a complete mess, but again I'm trying to figure out if it's best to just quit, so any help would be appreciated.

Thanks in advance.

Upvotes: 1

Views: 1867

Answers (1)

Christian Ternus
Christian Ternus

Reputation: 8492

The logic I'm trying to follow is that since strings in C are just characters in an array, the characters that should be an initial will come after the '\0' value.

In C, \0 denotes the end of a string, so you definitely don't want to be looking for that value.

Let's think about the logic. Someone's initials are probably:

  • the first character in the string
  • the first character after a space

– i.e. "Albus Percival Wulfric Brian Dumbledore" -> "APWBD" –

so you'll want to loop over the string, looking for either:

  • a space, in which case you'll want to grab the next letter, or
  • the end of the string ('\0') in which case you'll want to stop.

Edge cases to watch out for:

  • what happens if the string is empty?
  • what happens if the string ends with a space? (this might not happen if you're guaranteed to get properly formatted input)

Please don't get discouraged – we were all beginners once. This kind of thinking isn't always straightforward, but the answer will come eventually. Good luck!

Upvotes: 5

Related Questions