当前位置:网站首页>The C programming language (2nd) -- Notes -- 1.9
The C programming language (2nd) -- Notes -- 1.9
2022-07-27 11:31:00 【YovaVan】
1.9 A character array
The character array is C The most common array type in . The following programming explains the usage of character arrays and functions that operate character arrays . The program reads in a set of text lines , And print the longest line of text . Algorithm framework :
while( There are still unprocessed rows )
if ( This row is longer than the longest row that has been processed )
Save the longest line of this behavior
Save the line length
Print the longest line It can be seen from the above that , The program is divided into several sections , , respectively, Read in new line 、 Test read in rows 、 Save the row , The rest is Control this process .
Because the division method is more reasonable , Press this to program . First compile an independent function getline Read Enter the next line . Try to keep this function available in other occasions . At least ,getline The function must return a signal when it reads to the end of the text ; It can even return the length of a line of text when reading it , Or return when encountering the text terminator 0. because 0 Is not a valid line length , Therefore, it can be used as the return value to mark the end of the file . Each line contains at least one character ; Even lines that contain only newline characters , The length of 1.
When a Newly read line Compared with what I read before Longest line For a long time , This line needs to be saved . namely , The second function is required ,copy function , Copy the new line to a safe location .
Last , Need one main Main program to control getline and copy function . Programming :
#include <stdio.h>
#define MAXLINE 1000 /* Maximum input line length.*/
int getline(char line[], int maxline);
void copy (char to[], char from[]);
/* Print the longest input line.*/
int main()
{
int len; /* [Current line] Length.*/
int max; /* Maximum length [seen so far]. */
char line[MAXLINE]; /* Current input*/
char longest[MAXLINE]; /* Longest line saved here.*/
max = 0;
while ((len = getline(line, MAXLINE))>0)
if (len > max)
{
max = len;
copy (longest, line);
}
if (max > 0) /* There was a line.*/
printf("%s, longest");
return 0;
}
/*getline: Read a line into s, Return length.*/
int getline(char s[], int lim)
{
int c, i;
for ( i = 0; i < lim-1&(c = getchar()) != EOF &c!='\n'; ++i)
s[i] = c;
if (c == '\n')
{
s[i] = c;
++i;
}
s[i] = '\0';
return i ;
}
/*copy: Copy 'from' into 'to'; Assume to is big enough.*/
void copy(char to[], char from[])
{
int i;
i = 0;
while ((to[i] =from[i]) != '\0')
{
++i;
}
}
stay Beginning of program The statement getline and copy function , Suppose they are in the same file .
main And getline Functions pass through A pair of parameters And A return value Exchange data .getline function Two parameters Through the program line
int getline(char s[], int lim)Statement : Parameters 1—— s Declared as an array , Parameters 2—— lim Declare as integer , The statement provides Array size Is the purpose of Leave storage space . stay getline The function does not specify an array s The length of is because the size of the array is main Function settings . Same as power function ,getline The function uses a return Statement will Value is returned to its caller . The above program line also declares getline The return value type of the function is int. Because the default return value of the function is int, therefore int You can omit .
There are some The function returns Useful values , And some functions ( Such as copy) Only used to perform some actions , and No return value .copy Function return value type is void, It explicitly states : This function does not return any value .
getline Function handle character '\0'( That is, empty characters , Its value 0) Insert at the end of the array it creates , Mark the end of the string . This agreement has been C Language adoption :C Language appears similar to
"hello\0"Of Character constant , it Will be stored as a character array , Each element of the array stores each character of the string , And '\0' Marks the end of the string .
| h | e | l | l | o | \n | \0 |
printf Normal format in function ——%s Regulations : The corresponding parameter must be a string in this form .copy The function implementation depends on the input parameters '\0' End this fact , It will '\0' Copy to output parameters .( namely , Null character '\0' Not part of ordinary text .)
It is worth mentioning , Even such a small program as the above , There are also some troublesome design problems when passing parameters . Such as , When the length of the read line is greater than the maximum allowed ,main How should the function handle ?getline Function execution is safe , Whether the newline character is reached or not , Array full It will stop reading characters .main The function can determine whether the current line is too long by testing the length of the line and checking the last character returned , Then deal with it according to the specific situation . To simplify the procedure , This problem is not considered here .
call getline The program of the function cannot predict the length of the input line , therefore getline The function needs to check whether it overflows . On the other hand , call copy Function program knows ( Or you can find out ) Length of string , Choose not to add error checking to this function .
practice 1-16 Modify the main program of the program that prints the longest line of text main, Make it possible to print the length of input lines of any length , And print as much text as possible .
practice 1-17 Programming , Print length greater than 80 All input lines of characters .
practice 1-18 Programming , Delete spaces and tabs at the end of each input line , And delete lines that are completely blank .
practice 1-19 Write function reverse(s), The string s The order of the characters in is reversed . Write a program with this function , Reverse the order of characters in one input line at a time .
边栏推荐
- 最长上升子序列模型 AcWing 1017. 怪盗基德的滑翔翼
- ethereum rpc
- 数字三角形模型 AcWing 1027. 方格取数
- Summary of C language knowledge involved in learning STM32F103 (link only)
- 高斯消元 AcWing 884. 高斯消元解异或线性方程组
- Inclusion exclusion principle acwing 890. divisible numbers
- Knapsack problem acwing 9. grouping knapsack problem
- Instructions for mock platform
- Today's code farmer girl learned notes about event operation and ref attribute, and did the practice of form two-way binding
- Solve importerror: cannot import name'abs'import tensorflow error
猜你喜欢

The longest ascending subsequence model acwing 1017. The glider wing of the strange thief Kidd

Internal and external troubles of digital collection NFT "boring ape" bayc

Installation and use of GTEST and gmock

The C programming language (2nd) -- Notes -- 1.6

高斯消元 AcWing 884. 高斯消元解异或线性方程组

第13章 IO流

求组合数 AcWing 886. 求组合数 II

Gaussian elimination acwing 884. Gaussian elimination for solving XOR linear equations

KEPServer配置

求组合数 AcWing 889. 满足条件的01序列
随机推荐
Digital triangle model acwing 1015. Picking flowers
A deep analysis of the soul of C language -- pointer
First experience of three.js: simulating the growth of a small branch
(5) Printf (instead of echo)
背包问题 AcWing 9. 分组背包问题
Find the combinatorial number acwing 889. 01 sequence satisfying the condition
XXX packages are looking for funding run 'NPM fund' for details solutions
Remember an experience of using canvas to make the banner streamer effect of Tencent cloud homepage
The longest ascending subsequence model acwing 1016. The sum of the largest ascending subsequence
求组合数 AcWing 887. 求组合数 III
PAT(乙级)2022年夏季考试
WGet warning: unable to verify
Miscellaneous records of Finance
第12章 泛型
Properties file
15th largest value of data flow
Find the combination number acwing 888. find the combination number IV
Instructions for mock platform
最长上升子序列模型 AcWing 1010. 拦截导弹
State compression DP acwing 91. shortest Hamilton path