Home >Backend Development >C++ >Usage of cin.getline function in c++

Usage of cin.getline function in c++

下次还敢
下次还敢Original
2024-04-28 19:06:14941browse

The cin.getline() function reads a line of characters from standard input until the newline character or the specified maximum number of characters. Specific usage: char str[100];cin.getline(str, 100);

Usage of cin.getline function in c++

##cin.getline() function usage

Introduction:

The cin.getline() function is a function in C used to read a line of characters from standard input. This function reads characters from the stream until a newline character ('\n') is encountered or the specified maximum number of characters is reached.

Syntax:

<code class="cpp">istream& cin.getline(char *str, int num);</code>

Parameters:

  • str: ​​ points to the character array Pointer to store the row read from the stream.
  • num: Specifies the maximum number of characters in the character array, including the '\0' terminator.

Return value:

Returns the istream object representing the stream status. If the row is read successfully, the object represents normal status; otherwise, it represents an error status.

Usage:

Usually use the cin.getline() function to read user input from the keyboard. The specific usage is as follows:

<code class="cpp">char str[100];
cin.getline(str, 100); // 从标准输入读取一行并存储在 str 中</code>

Note:

    The cin.getline() function will automatically skip any spaces or newlines in the stream.
  • If the input line length is greater than the maximum number of characters, the function truncates the line and discards the remaining characters.
  • If the maximum number of characters is reached without encountering a newline character, the function continues reading until a newline character is encountered or the end of file is encountered.

The above is the detailed content of Usage of cin.getline function in c++. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn