Acc. to this post, the most used method to store text in a 2D array is by using %s approach. But, this approach has a downfall, i.e. whenever you press spacebar, the text which is typed after goes into the second element of array. for e.g. you typed
Input:-
1st element of char array = Hi everyone
Output:-
1st element of char array = Hi
2nd element of char array = everyone
Expected output:-
1st element of char array = Hi everyone
So, i want to ask why the below written approach cannot be used to enter text into a 2D array?
#include <stdio.h>
int main()
{
char ch[20];
printf("Enter name:");
scanf("%19[^\n]", ch);
printf("Your name is: %s", ch);
return 0;
}
If the above approach can be used, then please let me know how?
Please do not introduce pointer concepts/code in answer to this post. This is a question to understand why the above written approach fails.
Consider this as the code which fails:-
#include <stdio.h>
int main()
{
char name[4][20];
int i;
printf("Enter names:-\n");
for(i=0; i<4; i++)
{
printf("Enter name %d: ", i);
scanf("%19[^\n]", name[i]);
printf("\n");
}
for(i=0; i<4; i++)
{
printf("Entered name %d: %s", i, name[i]);
printf("\n");
}
return 0;
}
The above program compiles without any error or warning, but fails during runtime.