[The difference between cin, cin.get(), cin.getline(), and getline() in C++]

Article directory

    • introduce
    • cin
      • Basic usage
      • Enter multiple variables
      • Newline characters are stored in the buffer
    • cin.get()
      • Basic usage
      • Overloaded functions
      • Newline character left in buffer
    • cin.getline()
      • Basic use
      • Overloaded functions
      • Newline characters are not left in the buffer
    • getline() in string stream
    • Summarize
      • Usage summary
      • Several input examples
        • Input format
        • Input format
        • Input format
        • Input format
      • Output format
    • write at the end

Introduction

In problem programming in ACM mode, we need to solve the input and output problems of the program ourselves. The input of our own solution program is actually to input data from the keyboard, and then transfer the input data to the variables we define. The brief process is as follows:

  • When using the input stream cin or other input functions to read data from the keyboard, the program will make a request to the operating system to obtain input, which is the blinking input prompt on the terminal (screen) after the program is run. ;
  • Type a few characters by tapping the keyboard;
  • When we want to end character input, press the Enter key;
  • The operating system puts the data entered by the user into the input buffer at once;
  • C++ programs read data from buffers through cin or other input streams.

The variable needed when the code is running may be a character, an integer, a string with spaces, etc. We can input these through the keyboard and press the Enter key to put them into the input buffer, but Different input streams or input functions have different effects on data read from the buffer.

  • What kind of input stream or input function should we use if we want to read multiple data in space-separated buffer data?
  • If we want to read the data before the specified character in the buffer, what kind of input stream or input function should we use?
  • If we want to read data line by line in a buffer, what kind of input stream or input function should we use?

If you can easily deal with the above three problems, then you are awesome. You have basically mastered the commonly used operations of reading data from the standard input stream in cpp. You can also take a look at this blog post to review. If the answers to the above questions are not clear, then students must read this article carefully.

Next, let’s get to the point and take a look at the different effects of different input streams or input functions reading data from the buffer.

cin

Basic usage

Let’s first introduce one of the most commonly used standard input stream objects in C++, cin.

We often use cin >> num to read data from the buffer into num. The variable type of num can be of many types. Commonly used ones include int, string, char, double, float, etc.

Let’s look at a small example first:

#include <iostream>
using namespace std;

int main() {<!-- -->

    int n;

    cin >> n;
    cout << "n = " << n << endl;

    return 0;
}

In this example, we input an integer character from the keyboard (for example, 9), press the Enter key, the integer character will be stored in the buffer, and then use cin to read the data in the buffer, and finally output "n = 9" to the terminal window through the standard output stream cout.

cin reads data from the buffer, reading the string between the first non-whitespace character and the first terminator. The end character can be a space, a tab character at the beginning, or a newline character. Spaces, tabs, and newlines are the built-in cin end characters. If you want to use other characters to end reading data early, you need to customize them.

Enter multiple variables

cin reads data directly from the buffer. If there is still data in the buffer, we do not need to request keyboard input and read data directly from the buffer. For example, in the following example: we enter the first string separated by spaces, and then enter the second string. The corresponding code and output results are as follows.

#include <iostream>
using namespace std;

int main() {<!-- -->

    char s[100];
    cout << "Please enter a string:" << endl;
    cin >> s;
    cout << s << endl;

    cin >> s;
    cout << s << endl;
    return 0;
}



Since cin stops reading input when it encounters a space or tab character (/tab), the first cin will only Read the first string (the string starting with the first non-whitespace character and ending with the next whitespace character). There is still residual data in the buffer at this time, so the next cin will read data directly from the buffer without requesting input.

Using this principle, we can read multiple data from the buffer data separated by spaces or tabs.

Line breaks are stored in the buffer

Only when the corresponding terminator is pressed will the data be read from the buffer into the variable. cin reads a string from the buffer each time, using spaces as characters or string separators. Note that the last newline character will be placed in the buffer. Take the example below, where we use cin.get() to read a single character from the buffer.

#include <iostream>
using namespace std;


int main() {<!-- -->

    char s1[100], s2[100], ch;
    cout << "Please enter a string:" << endl;
    cin >> s1 >> s2;
    cout << s1 << endl;
    cout << s2 << endl;

    cin.get(ch);
    cout << (int)ch << endl;
    return 0;
}

We enter "cc ff" from the keyboard, and then press the Enter key. The data in the buffer is "cc ff\\
"
, and we will The buffer strings "cc" and "ff" are passed to s1 and s2 respectively. , the newline character is passed to ch. The final output result is as shown in the figure below. Because the ASCII code of the newline character is 10, a 10 will be output in the end.



cin.get()

Basic usage

cin.get() is a function in the C++ standard library that gets characters from an input stream, including whitespace characters (such as spaces, tabs, and newlines). Unlike cin, cin.get() does not treat tab characters, whitespace characters (spaces) as input terminating flags, so you can use it to get include An entire line of text including whitespace characters. By default, cin.get() uses the newline character (\\
) as the delimiter (the terminator that terminates the read data), indicating that a newline is read The time ends.

Run the following code, then enter 123 456, and then press the Enter key. The output result is as shown in the figure:

#include <iostream>
using namespace std;


int main() {<!-- -->

    char s1[100];

    cin.get(s1, 100);
    cout << s1 << endl;

    return 0;
}



Similar code, if we use cin to read the buffer data, it will only output "123".

Overloaded functions

The get() function defined in the header file has the following overloaded forms:

//single character (1) Read a single character from the standard stream;
int get();
istream & amp; get (char & amp; c);

// c-string (2) Read the string from the standard stream and store it in the c standard s string;
istream & get (char* s, streamsize n);
istream & get (char* s, streamsize n, char delim);

// stream buffer (3)
istream & amp; get (streambuf & amp; sb);
istream & amp; get (streambuf & amp; sb, char delim);

We most commonly use cin.get() to read a single character from the standard input stream and read multiple characters stored in a C standard string.

Line breaks remain in the buffer

Both cin.get() and cin will end reading data from the buffer when they encounter the corresponding terminator. They do not process newline characters, and newline characters will remain in the buffer. If you don’t want to read data from the previous buffer next time, you can use cin.ignore() to ignore the data in the previous buffer, or use cin.getlin().

cin.getline()

Basic usage

cin.getline() is a function in the C++ standard library that reads a line of text from an input stream and allows you to specify a delimiter character to end the reading. The default delimiter is the newline character (\\
), which means reading ends when the newline character is reached. But you can specify a custom delimiter character by supplying the third argument.

Overloaded functions

The getline function defined in the header file has the following two overloaded forms:

istream & getline (char* s, count n);
istream & getline (char* s, count n, char delim);

The function is: Read at most n characters (including the end marker ‘\0’) from istream and save them in the array corresponding to s. In fact, only from the input Read at most n-1 characters from the stream into the array s, because the last character must be the end identifier '\0', which is the last character in all strings in C language.

Line breaks will not remain in the buffer

The use of cin.getline() is basically the same as cin >> and cin.get(). The only difference is that when cin >> and cin.get() encounter the terminator and terminate reading data from the cache area, the newline character will remain. in the buffer, while using cin.getline() newlines are not left in the buffer.

Now we use getline to read data from standard input:

#include <iostream>

using namespace std;

int main() {<!-- -->

    char str[100];
    cin.getline(str, 100);
    cout << "str = " << str << endl;
    
    char c = cin.get();
    cout << (int)c << endl;
    
    return 0;
}

We run the above code, enter any string, such as “123 589”, press the Enter key, and “str = 123 589” will appear on the screen (left picture). When we press the Enter key again, 10 will appear on the screen (picture on the right).




If, we execute the following code:

#include <iostream>

using namespace std;

int main() {<!-- -->

    char str[100];
    cin.get(str, 100);
    cout << "str = " << str << endl;
    
    char c = cin.get();
    cout << (int)c << endl;
    
    return 0;
}

The output result is:



Why there is such a difference is because with cin.getline() , newline characters are not left in the buffer.

In the first piece of code, we also need to read a character from the buffer. There are no characters in the buffer, so a prompt for input will appear. We press the Enter key (line feed) and the output is on the screen. The ASCII code of the Enter key (line feed) we pressed.

In the second piece of code, we use cin.get() to read data from standard input, press the enter key (newline character), and the string in the buffer is passed to str. At this time, the newline character will remain in the buffer. At this time, a character needs to be read from the buffer, so it is logical to pass the newline character to c, and it will continue on the screen. The ASCII code of the newline character is output.

getline() in string stream

There are also getline() functions in the header file. Their usage is basically the same as in , with only three differences:

  • Differences in header files;
  • There is an additional first parameter istream is in getline(), which is usually filled in with cin, indicating that data is read from the standard input stream;
  • The received string variable in getline() is string, not char*. In C++ code, it is recommended to use getline(), because the variable receiving the string is string, which is a type that can be dynamically expanded.

Except for the above three differences, other usages are consistent with the usage of cin.getline(), including getline() which will not leave newline characters in the buffer.

Summary

Usage summary

cin.get() and cin.getline() are in the input stream and need to include the header file before use. cin is in the input and output stream, and you need to include the header file before using it. getline() is a string stream, and you need to include the header file before using it.

To read single or multiple variables (separated by spaces, tabs, or newlines) from standard input, especially integer variables, or to read integer variables from multiple lines into an array, use cin.

To read a single character from standard input, it is recommended to use cin.get() on the input stream.

To read single-line strings or multi-line strings from standard input, it is recommended to use getline() in the string stream.

cin and cin.get() will leave newline characters in the buffer, but getline() and cin.getline() will not.

Several input examples

Input format

The first line contains two non-negative integers m and n. They represent the length and width of the array respectively.

The next m lines contain n integers in each line.

In ACM programming, the most common thing is to input m rows and n columns of data into an array from the keyboard. The following is to input int from the keyboard. Code for integer data.

#include <iostream>
#include<vector>

using namespace std;

int main() {<!-- -->

    int m, n;
    cin >> m >> n;
    vector<vector<int>> grids(m, vector<int>(n));
    
    for (int i = 0; i < m; + + i) {<!-- -->
        for (int j = 0; j < n; + + j) {<!-- -->
            cin >> grids[i][j];
        }
    }

    /* This code is used to test whether the input is correct
    for (int i = 0; i < m; + + i) {
        for (int j = 0; j < n; + + j) {
            cout << grids[i][j] << " ";
        }
        cout << endl;
    }
    */
    
    return 0;
}

There are two ways for us to enter data in the command line window:

  • The first one: Enter all the data in one row, the first number is the number of rows m, the second number is the number of columns n, the next is the number in all columns of the first row, and then the number in the second row numbers in all columns until all numbers in m rows and n columns have been entered (two adjacent numbers are separated by spaces);
  • Second type: Enter the number of rows m and the number of columns n (separated by spaces) in the first line, press the Enter key, enter n numbers in each of the next m lines, and press Return after each line of numbers. car key;
  • The last Enter key pressed is stored in the buffer.
Input format

The first line contains two positive integers

m

,

n

m,n

m, n, respectively represent

A

A

A string sum

B

B

B The length of the string.

The second line is a length of

m

m

m string

A

A

A.

The third line is a length of

n

n

n string

B

B

B.

Both strings consist only of lowercase letters and

*

\texttt *

* Composed of

*

\texttt *

* indicates that the corresponding location is incomplete.

#include <iostream>
#include <string>
using namespace std;


int main() {<!-- -->

    int m, n;
    string A, B;
    cin >> m >> n >> A >> B;

    // // Test whether the input is correct
    // cout << m << " " << n << endl;
    // cout << A << " " << B << endl;
    return 0;
}
Input format

Multiline string.

Enter a string containing spaces in each line, enter multiple lines, and end the input when encountering “END”.

#include <iostream>
#include <string>
#include <vector>
using namespace std;


int main() {<!-- -->

    string str;
    vector<string> strs;
    getline(cin, str);
    while (str != "END" ) {<!-- -->
        strs.push_back(str);
        getline(cin, str);
    }
    
    // for test
    for (auto str : strs) {<!-- -->
        cout << str << endl;
    }

    return 0;
}
Input format

The input gives an unknown number of integers in a row whose absolute value does not exceed 1000.

Output format

Output the last occurrence of “250” in a line as the number (counting starts from 1). If the number “250” does not appear, the output is 0.

// #include <iostream>

// using namespace std;

// int main()
// {<!-- -->
// int ct = 0;
// int a, pos = 0;
// do
// {<!-- -->
// ct + + ;
// cin >> a;
// if (a == 250)
// pos = ct;
// }
// while (cin.get() != '\\
');
// cout << pos;
// return 0;
// }
 

#include <iostream>

using namespace std;

int main() {<!-- -->
  int cnt = 0;
  int a, pos = 0;
  while (cin.get() != '\\
') {<!-- -->
     + + cnt;
    cin >> a;
    if (a == 250) {<!-- -->
        pos = cnt;
    }
  }
  
  cout << pos;
  return 0;
}

Write at the end

If there are any errors in the content of the article or you have any questions about the article, you are welcome to send a private message to the blogger or point it out in the comment area .

If you have better time and space complexity methods, please share them in the comment area.

Finally, thank you for reading. If you feel you have learned something, you can give the blogger a thumbs up.