帮帮忙,是新手,这个怎么做??
Assignment 3 is an exercise in handling of dynamic arrays and strings. Submit (upload) a file with your source code. The file's name must be assgn3.c and it must be an ASCII text file for the upload to work.For reading of any user's input, use the code from Assignment 2 to read a word of at most 20 characters (i.e. it should not allow the user to enter more than 20 characters, not including the terminating '\n' and using the while-loop to clean up if the user does so). Thus, you need to read into a buffer of size 21. Turn the input word into a string by replacing '\n' with '\0'. Unlike in assignment 2, we must disregard empty input (when the user only strikes <enter> key).
When memory is being allocated (for the dynamic array, and then for each name), the allocation is performed using the standard function malloc() and it must be checked whether it worked or no. For that end use the macro merror()to simplify the program a bit:
Put at the top of your program a line
#define merror() {printf("memory allocation problem\n");exit(1);}
Then to test if allocation worked:
p = (char*) malloc(strlen(buffer)+1));
if (p == 0) merror();
Hence you will need to include three header files in your program
1. stdio.h for printf(), getchar() or fgetc(), fflush(stdout)
2. stdlib.h for exit() and atoi()
3. string.h for strlen() and strcpy()
If a number is to be read, read it as a word into the buffer, and then use the standard function atoi(buffer) to turn it into the appropriate number. For instance, if size is my variable for size, and buffer is my input buffer, size=atoi(buffer); will do the trick, of course, only after buffer was filled with the user's input.
1. The user is prompted for how many names he/she will enter.
2. Then a (dynamic) array of the requested size is created. It is an array of strings.
3. In a loop of the requested size
1. prompt the user to enter a name of at most 20 characters.
2. read the name and turn into a string.
3. allocate memory for a copy of the string and store its address in the appropriate item of the dynamic array.
4. copy the input string into the memory allocated.
4. When the loop is over, display the strings stored in the dynamic array.
5. Use bubble sort the sort the strings in the lexico-graphic order (like in Assignment 2, however we will just swap pointers rather than swapping strings by copying them).
6. Display the (sorted) strings.
how many names will be entered :
empty input
how many names will be entered :123456789012345678902134556677
input too long
how many names will be entered :3
you will enter 3 names
enter a name:
empty input
enter a name: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
input too long
enter a name: bill
enter a name: adam
enter a name: aaron
names as entered:
bill
adam
aaron
sorted names:
aaron
adam
bill