Use of character Arrays-read the text line and print the longest text line.

Source: Internet
Author: User

The idea is as follows:

While (there are still unprocessed rows)

If (the row is longer than the longest row that has been processed)

Save and change rows

Save the length of the row

Print the longest row

Here we use two self-compiled subfunctions: Getline and copy1. The Getline () function is used to read each row in the text line and return the length, copy1 () the function is used to save the longest row currently read to the specified longest character array.

The procedure is as follows:

# Include <stdio. h>
# Define maxline 1000 // Maximum length of the row that can be stored
Int Getline (char line [], int maxline); // Getline () function declaration
Void copy1 (char t0 [], char from []); // copy1 () function declaration
Main ()
{
Int max = 0, Len;
Char line [maxline], longest [maxline];
While (LEN = Getline (line, maxline)> 0)
If (LEN> MAX) // test whether the length of the entered character line is greater than the length of the line already entered
{
Max = Len;
Copy1 (longest, line); // Save the rows with the longest character length to the longest character array
}
If (max> 0)
Printf ("the longest output text line is: % s", longest );
}
Int Getline (char s [], int maxline) // Function Definition, reads a character from a row into the character array S, and returns its length
{
Int I, C;
For (I = 0; I <maxline-1 & (C = getchar ())! = EOF & C! = '/N'; ++ I)
S [I] = C;
If (C = '/N') // calculate the line break into the character Length
S [I ++] = '/N ';
S [I] = '/0'; //'/0' indicates the end of the string.
Return I;
}
Void copy1 (Char to [], char from []) // Function Definition, copy all characters in the from character array to the to character array
{
Int I = 0;
While (to [I] = from [I])! = '/0 ')
++ I;
}

Enter the following lines and the test result is as follows:

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.