-1

If you enter more than five characters in the "name" field the function giving the wrong output, otherwise if the input is less than or equal to five characters the function works just fine, or if I use just %s instead of reading five characters using %5s then also the function works.

Is there any fix available (I want to use %5s)?

#include<stdio.h>

int main(void)
{
  char name[6];
  int age;
  printf("Enter your name: ");
  scanf("%5s",name);
  printf("Enter your age: ");
  scanf("%d",&age);
  printf("Your name: %.4s\n",name);
  printf("Your age: %d\n",age);
  return 0;
}
Anton Menshov
  • 2,266
  • 14
  • 34
  • 55
arka
  • 418
  • 2
  • 9
  • 2
    Read user (or text file) input exclusively with `fgets()`. Forget `scanf()` exists. And if you must still use `scanf()` **do check the return value!** `if (scanf(...) != 1) /*error*/ exit(EXIT_FAILURE);` – pmg Sep 07 '21 at 07:47
  • Arka Mondal, If the user enters more than 5 characters for `name`, what would you like code to do with the excess characters? Exit the program? Eat them quietly? Whine and complain and ask again? Some names have spaces in them. How should code handle that? What should happen if input for `age` was non-numeric? Once questions, like these are answered, it is more clear how to read good input. – chux - Reinstate Monica Sep 07 '21 at 11:05

1 Answers1

1

It's good that you limit the input to five characters, as that will make it fit perfectly in the array you have (including the terminator). However, if the user inputs a longer string, the remaining will be left in the buffer and the input of the age will not work.

As a (relatively) simple way to improve input, use fgets instead to read a line but increase array size as it can include the newline itself. And that's kind of the point here: If the buffer contains the newline, then you know you have read the full string, can replace it with the string terminator, and then move on. However, if the buffer doesn't contain a newline, you need to "flush" the input buffer by reading all the remaining characters of the line and ignore them.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • Can you show me how I can use "fflush()" to flush the input buffer in that program to resolve the issue ? Thank you. – arka Sep 07 '21 at 10:45
  • 1
    @ArkaMondal Unfortunately the term "flush" is kind of misleading here... While what we want to do is to flush the buffer (or at least discard all characters until newline) we can't use the `fflush` function. The C specification says that calling `fflush` with an input-only stream (like `stdin`) leads to *undefined behavior* Instead you need to read character by character until you have read the newline (or have gotten an `EOF`). Also remember that all character-reading functions returns an **`int`**, just so it can be compared to the `int` value `EOF`. – Some programmer dude Sep 07 '21 at 12:26