0

I am an absolute beginner to programming and I am starting with the C language. I am currently using the Beginning Programming with C for Dummies book by Dan Gookin.

When doing an exercise with fgets() the following occurred.

This is my code

#include <stdio.h> int main() { char name[10]; printf("Who are you? "); fgets(name,10,stdin); printf("Glad to meet you, %s.\n",name); return(0); } 

The expected result should be a name with a full stop at the end and what is happening is that the full stop carries over to the next line like shown below.

enter image description here

I am using the code blocks IDE on Ubuntu

8
  • 2
    man fgets: "If a newline is read, it is stored into the buffer." Commented Feb 18, 2017 at 3:14
  • Just remove the newline from fgets? Commented Feb 18, 2017 at 3:22
  • 2
    A reliable way to get rid of the newline is name[strcspn(name, "\n")] = '\0';. Commented Feb 18, 2017 at 3:42
  • 1
    @JonathanLeffler OP would also have to include <string.h> to use strcspn(). Commented Feb 18, 2017 at 4:02
  • 1
    @RoadRunner: true, that would also be needed. Commented Feb 18, 2017 at 4:05

2 Answers 2

1

You typed Miguel and then pressed ENTER. name now holds Miguel\n, in which \n stands for the ENTER you just pressed, since ENTER counts as a character too. If you want to remove it, you'll find the answer here.

Sign up to request clarification or add additional context in comments.

Comments

0

You can use strtok(name, "\n")

1 Comment

This would fail if the user typed more then 8 characters before pressing the enter key or hit Ctrl-D.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.