1

I'm trying to write a very simple program which asks you to type your name and then it greets you. The code is the following:

#include <stdio.h>

int main() {
    char name[30];
    printf("Write your name: ");
    fgets(name, 30, stdin);
    printf("Hello, %s. Nice to meet you.\n", name);
    return 0;
}

But when I compile and run the program the following output is shown (typing the name John Doe):

Hello, John Doe
. Nice to meet you.

At first I was going to use gets() which apparently doesn't print the newline charcater, but the compiler (GCC) complained about it:

the `gets' function is dangerous and should not be used.

How can I remove the newline character from a string entered with fgets()?

1 Answers1

6

Add this line of code name[strlen(name)-1]='\0'; After fgets(). The newline happens because terminal symbol in fgets() is \n not \0 .So we need it to make it \0.

Modified code :-

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

int main() {
    char name[30];
    printf("Write your name: ");
    fgets(name, 30, stdin);
    name[strlen(name)-1]='\0';                        // making '\n' '\0'
    printf("Hello, %s. Nice to meet you.\n", name);
    return 0;
}

Output :-

Write your name: world
Hello, world. Nice to meet you.
anoopknr
  • 3,177
  • 2
  • 23
  • 33