-3

I was wondering if fgets() reads a new line char from user input, i.e. the keyboard. Here is some sample code I wrote:

while (1) {
  char userInput[3] = {'\0', '\0', '\0'};

  fgets(userInput, 3, stdin);
  flushStdin();
  printf("%s\n", userInput);
}

If I type '2', I am reprompted to enter another char, and the following result is:

$ 2
$ 3
  2

$

I understand how fgets() work, so it may be that my logic is incorrect. The desired output is:

$ 2
  2

$
Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
darylnak
  • 239
  • 4
  • 14
  • 3
    Where does the `$` come from? There seems to be more to your code than you are showing. Please provide a [mcve]. – kaylum Feb 07 '17 at 00:58
  • I don't understand your question, `fgets()` reads a whole line or `3` characters if they are inserted first. So it's wither, read until a `'\n'` or until there is no more room in the target buffer. – Iharob Al Asimi Feb 07 '17 at 00:59
  • 1
    What is `flushStdin()`? You [cannot do that](https://stackoverflow.com/questions/2187474/i-am-not-able-to-flush-stdin) without invoking undefined behaviour (eg `fflush(stdin)`) or using platform specific API.. – Ken Y-N Feb 07 '17 at 01:02
  • Try `printf("%d %d %d\n", userInput[0], userInput[1], userInput[2]);` to see what was read. – chux - Reinstate Monica Feb 07 '17 at 03:22

1 Answers1

0

I think fgets() will read up to 1 less than the buffer size given. It will take the \n from the input when you hit enter. You could use something like this to cleanse the input for strings or use scanf() for int input

void readLine(char* buffer, int bufferLength, FILE* file)
{
    fgets(buffer, bufferLength, file);

    int len = strlen(buffer);
    if(len > 0 && buffer[len - 1] == '\n'){
        buffer[len - 1] = '\0';
    }
}
NathanAck
  • 351
  • 3
  • 9
  • `fgets` reads a `size_t` number of bytes (not `int`), and similarly `strlen` returns a `size_t`. There's an easier way to *cleanse the input*: `buffer[strcspn(buffer, "\n")] = '\0';`. Mind you, this actually hinders one of the handling mechanisms of `fgets`; when `'\n'` *isn't found*, you need to remember you're only dealing with a *partial line*, and think about what *the next data* might be... – autistic Feb 07 '17 at 02:09
  • @Seb `char *fgets(char *str, int n, FILE *stream)` uses `int` for `n` bytes, not `size_t`. – RoadRunner Feb 07 '17 at 03:11