Cprimerplus 11th Chapter 10th question

Source: Internet
Author: User
Tags strcmp

Topic:

Write a program that reads input until 10 strings are read or EOF is encountered, and the read process is terminated by the one that is first satisfied in both. This program provides the user with a menu of 5 options: Output A list of initial strings, output strings in ASCII order, output a string in ascending order of length, output a string by the length of the first word in a string, and exit. The menu can be looped until the user enters an exit request. Of course, the program should be able to really complete the menu functions.

1. Complete the first section and read into the string.

It is intended to use pointer arrays to store strings, define and initialize the pointer string (the pointer needs to be initialized, the pointer array is also, afraid to become a wild pointer, so just start all point to null, found later on, so still use malloc allocated memory to the pointer bar).

    Char *str[];      for (i=0; i<; i++)         = (char *)malloc(nsizeof(char));

Read the strings as required, or read the 10 strings and stop reading them. The result is no, because the function gets (PTR) returns null if EOF is found, does not read EOF in and makes the pointer ptr point (for example, I commanded get () to read the EOF symbol, he encountered the EOF symbol and did not read it, but ran back to tell me that the concubine can not do ah ~).

     while (j<  &&  (*str[j]!=EOF))    {        gets (str[j]);        J+ +;    }

So modify the condition in the while (), and the modified while () condition already contains the Get () function, each time the judgment has been executed once, so the next loop in the Get () to delete, only left J + + is good.

     while (j<)&& (gets (str[j])! = NULL)) // (*str[j]!=eof) this as a judgment is not a drop        j + +;

2. Design the idea of main function, analyze the logic, and write the main function part. The main thing is to use the IF and else combination to select the classification, you should be careful to choose out of range of options. The code is as follows

 while(SCANF ("%c", &choice) = =1)    {        if(Choice <'a'|| Choice >'e') printf ("choice must be between ' a ' and ' E ' \ n"); if(Choice = ='e') Exit (1); Else        {            if(Choice = ='a') Print_orig (str); if(Choice = ='b') print_as_ascii (str); if(Choice = ='C') Print_as_strlen (str); if(Choice = ='D') Print_as_1strlen (str);    } getchar (); //clear the Enter key to confirm the line break character when enteringPuts"Make your choice (A, B, C, D, E):");    Print_table (); } puts ("fail reading the choice, good bye!"); return 0;}

3. Write each sub-function separately

3.0 Print the table header, this simple, is the printf function can

/* ****************************** Print Header ************************** */ void print_table (void)    {    printf ("a) print original text              b) Print lines in order of ascii\n");    printf ("c) Print lines in order of strlen   D) Print lines in order of first word ' s len\n
   
     "
    );    printf (
    "
    e) exit\n
    "
    );}
   

3.1 Printing The original string, since the beginning of the consideration of the use of the pointer array, so that the pointer to print it (Loop puts (Str[i] several times))

/* ************************* Print the original string ************************* */ void Print_orig (char *str[]) {    int  i;      for (i=0; i<lines; i++)        puts (Str[i]);}

3.2 The string ASCII size to print the string, you need to sort the strings, this chapter explains the choice of sorting algorithm, here is just used, my previous blog also mentioned. The code follows, noting the note in the note. However, after ordering the pointer to change the position of the point, so after the selection of sorting and then want to print out the original string, you can not use the pointer. The way I can think of it is to use a set of pointers, point to these strings, change a set of pointers, do not change another set of pointers, the original string is printed with a constant array of pointers, the selection of the order is used to become a pointer array (time reason oneself did not get).

/********************* Print the strings by ASCII code *************************/voidPrint_as_ascii (Char*str[]) {    inti,j; Char*p_temp;  for(i=0; i<lines; i++)    {         for(j=i+1; j<lines; J + +)        {            if(Ascii_num (Str[i]) > Ascii_num (str[j]))//The reference answer is to use the strcmp () function to compare the ASCII code value of the string, I do not bother to write a function (actually did not think, whining ~ ~){p_temp= Str[i];//compared to Ascii_num (Str[i]) and Ascii_num (Str[j]), the Exchange is str[i] and str[j], there is a mapping relationship!! Mapping problems have bothered me for half a dayStr[i] =Str[j]; STR[J]=p_temp; }}} print_orig (str);}

3.3 String lengths are used to output strings, and the above routines are all the same, just use the strlen () function when comparing them. The code is as follows

/********************** Print strings by string length *********************/voidPrint_as_strlen (Char*str[]) {    inti,j; Char*p_temp;  for(i=0; i<lines; i++)    {             for(j=i+1; j<lines; J + +)        {            if(Strlen (Str[i]) >strlen (Str[j])) {P_temp=Str[i]; Str[i]=Str[j]; STR[J]=p_temp; }}} print_orig (str);}

3.4 Sort and output strings according to the length of the first word in the string, the same way as the previous one, just comparing the length of the first word. I did not carefully consider the specific situation, a simple write a function (the beginning is the space, even if 0), of course, consider clearly written carefully some of the best, but here I want to do for the purpose of the exercise, do not have to spend too much time (in fact, also wrote two or three days, whining ~, the heart annoyed him ~).

/******************** Print by the first word length in a string *********************/voidPrint_as_1strlen (Char*str[]) {    inti,j; Char*p_temp;  for(i=0; i<lines; i++)    {         for(j=i+1; j<lines; J + +)        {            if(First_len (Str[i]) >First_len (Str[j])) {P_temp=Str[i]; Str[i]=Str[j]; STR[J]=p_temp; }}} print_orig (str);}

3.5 in 3.2 and 3.4 of their own write two simple small programs, respectively, calculate the ASCII code value and the first word length, the code is as follows (casually written, not careful)

intAscii_num (Char* p)//computes the ASCII code value of a string{    intI,asciinum =0;  for(i=0; * (p+i)! =' /'; i++) Asciinum+=* (p+i); returnAsciinum;}intFirst_len (Char*P)//calculates the length of the first word in a string{    inti;  for(i=0; * (p+i)! =' '; i++); returni;}

4. Summary

The reference answer uses a two-dimensional array and pointer array, the input read into the two-dimensional array of pointers, and then the pointer array to each string, is a backup of the original file, and then toss the pointer is not afraid to damage the order of the original file or something. This is worth learning. The selection sort in the reference answer is basically the same as mine when it is implemented, but the switch-case combination is not used in the main function, but the library function strcmp (), Isalpha () is called, and the resource is not wasted. If-else

After debugging is able to complete the task, but the problem still has a drop, so I think it is in the beginning of the program to explain, after all, if you look back can be convenient to recall and clarify ideas, especially the program a little bit more complex (this is my own long-made program, I can see how much water.) But the road long its repair far XI, oneself slowly try to perfect oneself slowly, refueling ^_^).

Cprimerplus 11th Chapter 10th

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.