Introduction to getline function

Today, the editor will explain to you the relevant knowledge about the getline function.

Table of contents

一.cin.getline(char* s, streamsize n, char delim)

二.getline(istream& is, string& str, char delim)


The getline function and cin are complementary.

Compared with cin, the advantage of getline is that you can enter spaces when entering strings . And cin will automatically end the input when entering a space. This is very similar to the scanf and gets functions in the c language.

一.cin.getline(char* s, streamsize n, char delim)

The header file required for this function is <iostream>.

It can be understood that getline is a function of the cin class at this time, and the namespace it is in is std, so when inputting, it should be written as std::cin.getline().

The parameter char* s here is the input string variable, n is the number of characters in the input string (the nth complement '\0') , delim is the input termination condition, that is, the input is terminated when the character represented by delim is encountered .

Example:

char str[10];

cin.getline(str, 7, 'a');

When we enter sdfazsertyg, str will store sdf because we end when we meet a by default.

Similarly, when bcdefghijklm is input, str will store bcdefg because we stipulate that only 7 characters can be stored, and the 7th bit is filled with '\0'.

It is worth noting that char delim can be omitted in normal use , and the default value of C++ language is '\0'

二.getline(istream& is, string& str, char delim)

header file: <string>

is is the standard input stream function, str is the variable name used to store characters, and delim is the end sign, the function here is the same as that in cin.getline().

have to be aware of is:

getline() is a function of the string stream and can only be used for input operations of the string type.

cin.getline is a function of std stream, which is used for input operation of char* type.

In other words, when you define a variable of type string, you can only use getline() to input it.

When you define a char* type variable, it can only be input with cin/cin.getline().

The function is similar to cin.getline:


It is not easy to create, please support Sanlian if there is any mistake, please correct me

Guess you like

Origin blog.csdn.net/weixin_61857742/article/details/124382424