Problem: I have been trying to get characters as input from user and store it in a character array using the scanf()
function in c, but there is no value stored at index 0 of the array. I don't understand why this is happening. This is the code I am working with,
#include<stdio.h>
int main()
{
int n,i;
printf("Enter number of characters to store: ");
scanf("%d", &n); //length of character array
char ch_arr[n+1];
printf("Enter the string: ");
for(i=0;i<n+1;i++){
scanf("%c",&ch_arr[i]); //get characters from user
}
printf("You have entered: \n");
for(i=0;i<n+1;i++){
printf("Index %d = %c\n",i,ch_arr[i]); //print the character array
}
printf("\nThe character at index 2 is =%c",ch_arr[2]);
}
The output for the above code is
Enter number of characters to store: 5
Enter the string: stack
You have entered:
Index 0=
Index 1= s
Index 2= t
Index 3= a
Index 4= c
Index 5= k
The character at index 2 is =t
The character at index 2 should be a. There is no value store at index 0. Can anybody explain why this occur and how to solve this without using other ways to get input such as gets()
etc..