0
#include<stdio.h>

#include<stdlib.h>

int main() {
  int i, n;
  printf("Enter length of employee id:\n");
  scanf("%d", & n);
  char * arr = (char * ) malloc((n + 1) * sizeof(char));
  printf("Enter employee id:\n");

  //      scanf("%s", arr);
  for (i = 0; i < n; i++) {
    printf("Enter %dth character of employee id:\n", i + 1);
    scanf("%c", (arr + i));
  }

  for (i = 0; i < n; i++) {
    printf("%c", *(arr + i));
  }
}

In the given code I want to get input of each character of employee id one by one by one using a for loop and the scanf function. Somehow this isn't working. I know the input can be taken in the form of a string(that is why i have allocated (n + 1) terms while allocating the memory) but I want to know why isn't working in this case.

The output I am getting for n = 3 is:

Enter length of employee id:
3
Enter employee id:
Enter 1th character of employee id:
Enter 2th character of employee id:
d
Enter 3th character of employee id:

d

I cannot input the first and third character, why is this?

3limin4t0r
  • 19,353
  • 2
  • 31
  • 52
  • The overall approach you take for whatever problem you're trying to resolve looks odd. Please explain what you're _actually_ trying to achieve. – Jabberwocky Mar 31 '23 at 12:01
  • 1
    [Does this answer your question?](https://stackoverflow.com/questions/5240789/scanf-leaves-the-newline-character-in-the-buffer) – Dávid Laczkó Mar 31 '23 at 12:03
  • 1
    In the first `scanf` you enter a number and then press ENTER. This puts a newline in the input buffer. Then the first `scanf` for id is reading this newline. You should put a breakpoint to observe this. And also it is recommended to check the return value of `scanf` to verify it succeeded. – wohlstad Mar 31 '23 at 12:03
  • In your `scanf` formats, change `scanf("%c", ...)` to `scanf(" %c", ...)`. I.e. add a space before the `%c`. Otherwise you'll be picking up the newline characters. – Tom Karzes Mar 31 '23 at 12:04
  • 1
    @Jabberwocky I just want to take an id as input and print it, I know I can do that by using a string but I just don't know why isn't this method working. – Varad Tandale Mar 31 '23 at 12:05
  • OT: instead of `*(arr + i)` you should write `arr[i]`. It's the same thing, but latter is a more readable notation. – Jabberwocky Mar 31 '23 at 12:06
  • @Varad because `%c` instructs `scanf`to read *every character* without filtering, including the previous newline that you typed. Adding the space before `%c` instructs `scanf` to filter leading any whitespace. – Weather Vane Mar 31 '23 at 12:13

0 Answers0