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

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
MigL
  • 1
  • 2
    [man fgets](https://linux.die.net/man/3/fgets): "If a newline is read, it is stored into the buffer." – kaylum Feb 18 '17 at 03:14
  • Just remove the newline from `fgets`? – RoadRunner Feb 18 '17 at 03:22
  • Please don't post images for simple text output — include the text output in the question. Treat it as code. – Jonathan Leffler Feb 18 '17 at 03:41
  • 2
    A reliable way to get rid of the newline is `name[strcspn(name, "\n")] = '\0';`. – Jonathan Leffler Feb 18 '17 at 03:42
  • 1
    @JonathanLeffler OP would also have to include `` to use `strcspn()`. – RoadRunner Feb 18 '17 at 04:02
  • 1
    @RoadRunner: true, that would also be needed. – Jonathan Leffler Feb 18 '17 at 04:05
  • First of all let me thank you for your answers, I'm sorry It took me so long to come back here. The thing is I might not have explained myself correctly. Even if I remove the \n character (line9) the full stop after the %s still goes to a new line. And even stranger, at least to me, If I change the length of the string to 3 instead of 10 and write my name (Miguel) what is output is Mi. The first 2 letters of my name and the full stop. Any thoughts? Thanks – MigL Feb 23 '17 at 22:11
  • show your modified code that takes into account the above comments and still fails. – pm100 Sep 25 '18 at 23:50

2 Answers2

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.

MinhVP
  • 31
  • 6
0

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

jophab
  • 5,356
  • 14
  • 41
  • 60
H. Al-Amri
  • 179
  • 2
  • 8
  • 1
    This would fail if the user typed more then 8 characters before pressing the enter key or hit Ctrl-D. – alk Feb 18 '17 at 09:49