Summary of the getline function in C/C ++
The getline function is a common function. Based on its name, we can know that this function is used to read a row of data. Now we will summarize the getline function.
In the standard C language, the getline function does not exist.
The following is a simple C language implementation method: int getline _ (char s [], int lim ){
Int c, I;
I = 0;
While (c = getchar ())! = EOF & c! = '\ N' & I S [I ++] = c;
S [I] = '\ 0 ';
Return I;
}
The following is a simple test program: int test1 (){
Char s [100];
Int len;
While (len = getline _ (s, 100)> 0)
Printf ("% s \ n", s );
Return 0;
}
But there is a problem with this implementation, that is, it will also stop when there is a blank line.
To solve this problem, we need to reconsider the judgment conditions of the while loop.
In the above implementation, we stop EOF and newline '\ n', and judge whether to end by judging whether the length of the read string is greater than 0.
To read empty rows, we need to determine whether the EOF is read. If not, we can continue reading.
What is EOF?
EOF is in C language to distinguish between valid data and input Terminator.
The solution of C language is: when no input is made, the getchar function returns a special value, which is different from any actual character. This value is EOF (end of file, end of file ). When declaring the variable c, we must make it large enough to store any value returned by the getchar function. C is not declared as char because it must be large enough to store the file Terminator EOF in addition to any possible characters.
The EOF input is locked by the system. In windows, it is ctrl + z, and in linux/unix, It is ctrl + d.
The following is the modified getline function int getline2 _ (char s [], int lim ){
Int c, I;
I = 0;
While (c = getchar ())! = EOF & c! = '\ N' & I S [I ++] = c;
If (c = EOF & I = 0)
Return-1;
S [I] = '\ 0 ';
Return I;
} If it is the end of the file (c = EOF & I = 0), we will return-1, and determine whether to continue the input by judging whether the returned value is-1: int test1 (){
Char s [100];
Int len;
While (len = getline2 _ (s, 100 ))! =-1)
Printf ("% s \ n", s );
Return 0;
} In this way, all input values can be correctly read.
In the gcc compiler, the standard library is extended and a getline function is added. The function is defined as follows:
# Include
Ssize_t getline (char ** lineptr, size_t * n, FILE * stream); where * lineptr points to a dynamically allocated memory area. * N indicates the length of the allocated memory. If * lineptr is NULL, The getline function automatically allocates dynamic memory (ignoring the size of * n ), therefore, when using this function, pay attention to the memory release.
If * lineptr allocates memory, but the allocated memory is insufficient during usage, the getline function calls the realloc function to re-allocate the memory, update * lineptr and * n at the same time.
Note * lineptr refers to a dynamically allocated memory, which is allocated by malloc, calloc, or realloc. It cannot be a statically allocated array.
The following figure shows how to use this function. dynamic memory is allocated in advance. Void test2 (){
Int read;
Int len = 100;
Char * line = NULL;
If (line = malloc (len + 1) = NULL ){
Printf ("Can't get memory \ n ");
Exit (-1 );
}
While (read = getline (& line, & len, stdin ))! =-1)
Printf ("% s \ n", line );
Free (line );
}
The following is a case where the memory is not allocated in advance: void test3 (){
Int read;
Int len = 0;
Char * line = NULL;
While (read = getline (& line, & len, stdin ))! =-1)
Printf ("% s \ n", line );
Free (line );
}
Similarly, the memory will be released.
Note that the getline function reads the last line break. The previously written function does not include this. Next let's modify it and read the line break. Int getline3 _ (char s [], int lim ){
Int c, I;
I = 0;
While (c = getchar ())! = EOF & c! = '\ N' & I S [I ++] = c;
If (c = EOF & I = 0)
Return-1;
If (c = '\ n ')
S [I ++] = c;
S [I] = '\ 0 ';
Return I;
}
In this way, the line break is also read. In this case, the getline function is good.
For convenience, C ++ adds the getline function to the standard library.
In fact, in C ++, A getline function is defined for different input stream objects, namely:
Std: fstream: getline
Std: istream: getline
Std: ifstream: getline
Std: iostream: getline
Std: wfstream: getline
Std: Role Ream: getline
Std: wifstream: getline
Std: wiostream: getline
Std: stringstream: getline
Std: basic_fstream: getline
Std: basic_istream: getline
Std: istringstream: getline
Std: wstringstream: getline
Std: basic_ifstream: getline
Std: basic_iostream: getline
Std: wistringstream: getline
Std: basic_stringstream: getline
Std: basic_istringstream: getline
Here we will discuss the getline function of the standard input object. The situations of other objects are similar.
In the header file The getline function is declared as follows:
Istream: getline
Istream & getline (char * s, streamsize n );
Istream & getline (char * s, streamsize n, char delim );
A function is an array of the C type. Because function Overloading is allowed in C ++, multiple functions with the same name can exist. The delim parameter specifies the delimiter. If this parameter is not specified, '\ n' is used by default'
The following is an example:
Void test1 (){
Char line [100];
While (cin. getline (line, 100 ))
Cout < }
Note that the getline here is to read a blank character. But does not include the last line break.
C ++ also defines a global function in the std namespace. Because the getline function parameter uses a string, it is declared in The header file is in.
The statement is as follows:
Istream & getline (istream & is, string & str, char delim );
Istream & getline (istream & is, string & str );
A simple example is as follows:
Void test2 (){
String line;
While (getline (cin, line ))
Cout < }
Note that line breaks are not read here.
Therefore, the function for reading a row in C ++ does not read line breaks, while the getline function in GCC reads line breaks. It can be understood that it is generally not read, especially the GCC reading.
Getline () in C/C ++ ()Getline is not a C library function, but a C ++ library function. It generates a string that contains a string of characters read from the input stream until the generation ends in the following cases. 1) to the end of the file, 2) encounter the function delimiters, 3) the input reaches the maximum.
Note: When a function encounters a character that is equal to the Terminator, the function ends, and the function extracts the delimiters. In this case, the delimiters are neither placed back into the input stream nor into the string to be generated. Therefore, it can be understood that the first carriage return after the input is the delimiters, which are discarded after confirmation, and the second is required for normal program execution!
C ++ has the getline () function.
C has fgets (), gets (), and getline.
It is used to read a line of character until the line break, including the line break (the line break is replaced with '\ 0 ).
Usage conditions
Usage conditions in linux Standard C:
# Define _ GNU_SOURCE
# Include
Function declaration:
Ssize_t getline (char ** lineptr, size_t * n, FILE * stream );
Return Value
Success: return the number of bytes read.
Failed:-1 is returned.
Parameters:
Lineptr: pointer to the character storing this row. If it is NULL, the system will help malloc. Please release it free after use.
N: if the pointer is from the system malloc, enter 0.
Stream: file descriptor
#define _GNU_SOURCE#include
#include
ssize_t getline(char **lineptr, size_t *n, FILE *stream);int main(void){FILE *fp;char * line = NULL;size_t len = 0;ssize_t read;fp = fopen("/etc/motd", "r");if (fp == NULL)exit(EXIT_FAILURE);while ((read = getline(&line, &len, fp)) != -1){printf("Retrieved line of length %zu :\n", read);printf("%s", line);}if (line)free(line);exit(EXIT_SUCCESS);}
Cin. getline () in C ++ format ()
# Include
Using namespace std; int main () {cout <"Type the letter 'A':"; ws (cin); char c [10] = {'\ 0 '}; cin. getline (c, 10, '#'); // replace getline with get to try. This is a big difference between cout <
C ++ has two getline functions, which are defined in different header files respectively. 1. getline () is defined in
The number of rows in. It is used to enter a string and end with enter. Function prototype: getline (cin, str); cin: input stream object of the istream class str: string object to be input
// Chapter 4 Programming Exercise 1 # include in C ++ primary plus
# Include
Using namespace std; string fname; string lname; char grade; int age; int main () {cout <"What is your first name? "; Getline (cin, fname); cout <" What is your last name? "; Getline (cin, lname); cout <" What letter grade do you deserve? "; Cin> grade; cout <" What is your age? "; Cin> age; cout <" Name: "<
2. cin. getline (char ch [], size) is a member function of cin, defined in
Is used to input a string with the specified size in the row and end with enter. If the input length exceeds the size, subsequent input is no longer accepted.
// Chapter 4 Programming Exercise 1 # include in C ++ primary plus
Using namespace std; char fname [5]; char lname [5]; char grade; int age; int main () {cout <"What is your first name? "; Cin. getline (fname, 5); cout <" What is your last name? "; Cin. getline (lname, 5); cout <" What letter grade do you deserve? "; Cin> grade; cout <" What is your age? "; Cin> age; cout <" Name: "<