Question #45238
how to enter two or more names using two dimensional array?
1
Expert's answer
2014-08-21T04:33:05-0400
#include <cstring>#include <cstdio>#include <cctype>const int MAX_NAMES = 32;const int MAX_NAME_LENGTH = 128;typedef char Array2D[MAX_NAMES][MAX_NAME_LENGTH];void input_names(Array2D& names){   char buffer[MAX_NAME_LENGTH];   char choice;      /* Fill the 2D array of chars with zeros.    * Zero-char indicates the end of the ANSI string */   memset(names, 0, MAX_NAMES * MAX_NAME_LENGTH);      for (int k = 0; k < MAX_NAMES; k++)   {      /* Ask the user whether he/she wants to enter another name */      printf("Do you want to input a new name? (y/n): ");      do      {         scanf("%s", buffer);                  /* Validate user selection */         choice = tolower(buffer[0]);         if (strlen(buffer) == 1 && (choice == 'y' || choice == 'n'))            break;                     printf("Wrong choice. Please re-enter (y/n): ");      }      while (true);            /* Stop prompting for new names if 'n' was selected */      if (choice == 'n')      {         printf("\n");         return;      }            /* Ask the user to enter a new name otherwise */      printf("Enter a new name: ");      scanf("%s", names[k]);      printf("\n");   }   printf("The maximum number of names (%d) was reached.\n", MAX_NAMES);}void print_names(const Array2D& names){   for (int k = 0; k < MAX_NAMES; k++)   {      /* Break if the current one and all succeeding strings are empty */      if (names[k][0] == '\0')         break;      printf("%s\n", names[k]);         }}int main(){   Array2D names;   input_names(names);      printf("You've entered the following names:\n");   print_names(names);   return 0;}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!
LATEST TUTORIALS
APPROVED BY CLIENTS