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..
CodePudding user response:
The array stores the new line character '\n'
stored in the buffer after this call of scanf
scanf("%d", &n);
that corresponds to the pressed key Enter. It is seen from the output.
You could write this call for example like
scanf("%d%*c", &n);
Another approach is to change the loop the following way
for(i=0; i< n 1;i ){
scanf(i == 0 ? " %c" ? "%c",&ch_arr[i]); //get characters from user
}
Or if you want to store a string in the array then write
size_t i = 0;
for( ; i < n; i ){
scanf(i == 0 ? " %c" ? "%c",&ch_arr[i]); //get characters from user
}
ch_arr[i] = '\0';
Or if you do not want to enter a sequence with embedded spaces then you can write the call of scanf
simpler
size_t i = 0;
for( ; i < n; i ){
scanf( " %c",&ch_arr[i]); //get characters from user
}
ch_arr[i] = '\0';
Pay attention to the leading space in the format string. It allows to skip white space characters.