C programming language Exercise 1-16, c Programming 1-16

Source: Internet
Author: User

C programming language Exercise 1-16, c Programming 1-16

Exercise 1-16Modify the main program of the program that prints the longest text line to print the length of the input line of any length and print as much text as possible.

The Code is as follows:

#include <stdio.h> // Include information from the standard library.

#define MAXLINE 10

int getline (char line [], int maxline);

int main () // Define a function named main, which does not accept parameter values.
{
    int len;
    int max;
    char line [MAXLINE];
    while ((max = getline (line, MAXLINE))> 0)
    {
        printf ("The number of characters in the input line:% d. The content is% s \ n", max, line);
    }
    printf ("The program ends.");

    getchar (); // Prevent the console from flashing, you need to close the console after accepting arbitrary characters.
    return 0; // returns an integer to the execution environment, 0 means successful execution.
}

int getline (char s [], int lim)
{
    int c, i, j;
    j = 0;
    for (i = 0; (c = getchar ())! = EOF && c! = '\ n'; ++ i)
    {
        if (i <= lim-2) // If the array is filled with one left, then characters are not put into the array.
            s [i] = c;
        ++ j; // but the line character counter is still +1.
    }

    if (j> lim) s [lim-1] = '\ 0'; // If the length of the input character is greater than the length of the array, the last bit of the array is written as '\ 0'.
    else s [i + 1] = '\ 0'; // Otherwise, write '\ 0' after valid characters.
    return j;
} 

Personal Understanding:

The main purpose of the exercise is to understand the '\ 0' after the valid bits in the char array.


Related Article

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.