Hi
I need to a program which prompt for how many names the user will enter
Then a (dynamic) array of the requested size is created. It is an array of strings.
In a loop of the requested size
prompt the user to enter a name of at most 20 characters.
read the name and turn into a string.
allocate memory for a copy of the string and store its address in the appropriate item of the dynamic array.
copy the input string into the memory allocated.
When the loop is over, display the strings stored in the dynamic array.
problems:
1. i cant show " empty input" for the user to enter only "\n"
2. the loop cant run properly, it always trapped after i enter all the names
this is the work i done so far.
Thank you for the effort!
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define merror() {printf("memory allocation problem\n");exit(1);}
int main(void)
{
int num;
char p;
char **resp;
char buf[21];
int i, j;
printf(" how many names will be entered : \n");
fflush(stdout);
scanf("%d", &num);
fflush(stdin);
if (num ==0)
{
printf(" empty input \n");
}
else if (num>= 10)
{
printf(" input too long \n");
}
else if (num >0 && num<10)
{
printf("you will enter %d names \n", num);
}
for(i=0; i < num; i++)
{
printf(" enter the name \n");
for(j=0; j<21; j++)
{
buf[j]=fgetc(stdin);
if (buf[j]=='\n')
{
buf[j]='\0';
break;
}
}
if (j==21)
{
printf("input too long\n");
while(fgetc(stdin)!='\n');
continue;
}
}
for(i=0; i< num; i++)
{
for(j=0; j<21; j++)
{
**resp= buf[j];
}
}
printf("\names as entered: \n");
for(i=0; i<num; i++)
{
printf("%s\n",**resp);
}
return 0;
}