Thread: Entry and looping problems

  1. #1
    Registered User
    Join Date
    Mar 2008

    Question Entry and looping problems

    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!

    #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");
                    scanf("&#37;d", &num);
    	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++) {
    	      if (buf[j]=='\n')
    	    if (j==21)
    	      printf("input too long\n");
        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++)
    return 0;
    Last edited by liukinhei; 03-11-2008 at 03:13 PM.

  2. #2
    Dr Dipshi++ mike_g's Avatar
    Join Date
    Oct 2006
    On me hyperplane
    You dont seem to have allocated any space for resp. Have a look for malloc in the FAQ.

    You then need to allocate space and set resp inside the loop where you are gettig the list of names, otherwise each time you enter a new name all you will be doing is overwriting the last one.

    Also, you might find it simpler to use fgets to get a whole string in one go rather than doing it character by character.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help With C code looping
    By maker10 in forum C Programming
    Replies: 11
    Last Post: 10-23-2008, 10:57 PM
  2. Replies: 1
    Last Post: 10-17-2006, 08:03 AM
  3. looping do while
    By bazzano in forum C Programming
    Replies: 1
    Last Post: 03-07-2006, 01:46 AM