Hi! I need to create a program for several functions.
first ,The user is prompted for how many names he/she 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.
but after i run my program, it is trapped on the part which i finished input all the names. it doesnt show the names. Also, i dunno how to output the message "empty output" while the user enter nothing
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[i][j]= buf[j];
}
}
printf("\names as entered: \n");
for(i=0; i<num; i++)
{
printf("%s\n",resp[i]);
}
return 0;
}