-4

Here, I am trying to enter the first name and last name as "Firstname Lastname". I want to get the output as "Lastname, FN." where FN is the first letter of first name.

Example: Input= "James Garcia" ; Output="Garcia, J."

Please find the error in my code.

#include <stdio.h>

int main () {
    char fn[20],ln[20];

    printf("Enter a first name and a last name:");
    scanf("%c %s",&fn,&ln);

    printf("%s, %c.",ln,fn);


    return(0);
}
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • 3
    `Please find the error in my code`...ummm..no. '[help]. – Sourav Ghosh Jun 19 '18 at 07:56
  • Welcome to Stack Overflow! It looks like you forgot to enable a good set of warnings. For GCC, I recommend `-Wall -Wextra -Wwrite-strings` as a minimum; consider also `-Wpedantic -Warray-bounds` for identifying some other common mistakes. – Toby Speight Jun 19 '18 at 09:49

1 Answers1

3

You want this:

printf("Enter a first name and a last name:");
scanf("%s %s", fn, ln);        // you are reading two strings,
                               // not one char and one string
printf("%s, %c.", ln, fn[0]);  // you print one string and one char
                               // not two chars

Disclaimer: this is oversimplified code that does not do any error checking for brevity.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
  • 1
    Have an upvote, but also see this for a caution against using `scanf`: https://stackoverflow.com/questions/1621394/how-to-prevent-scanf-causing-a-buffer-overflow-in-c – Bathsheba Jun 19 '18 at 08:09
  • Thank you @Jabberwocky. But could you please tell me why do we put the [0] after the fn in the second printf to print the character . – Nikhil Boddupalli Jun 19 '18 at 08:24
  • @NikhilBoddupalli you need to read the chapter dealing with arrays and pointers and the chapter dealing with strings in your C text book. `fn` is the _address_ of the first character. `fn[0]` is the first character, `fn[1]` is the second character etc. – Jabberwocky Jun 19 '18 at 08:27
  • At the very least, I think this should check the return value of `scanf()` before relying on the variables having valid values, and also include size limits to avoid being open to buffer overruns. – unwind Jun 19 '18 at 08:39