Home > Backend Development > C++ > body text

Usage of cin.getline in c++

下次还敢
Release: 2024-04-26 16:15:26
Original
701 people have browsed it

The cin.getline() function is used to read a line of text from standard input into the specified string variable. Steps: Declare a character array to store text. Call cin.getline() on the cin object, passing the character array and the maximum number of characters. The terminating character '\0' is automatically added to the end of the text being read.

Usage of cin.getline in c++

Usage of cin.getline() in C

Introduction to cin.getline()

cin.getline() is a function in C that reads a line of text from the standard input (cin) and stores it in the specified string variable. It is a member function and belongs to the istream class, so it needs to be called on the cin object.

Syntax

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

Parameters

  • str: ​​ is used to store the read text character array.
  • num: The maximum number of characters to read (including the terminating '\0' character).

Return value

cin.getline() returns a reference to an istream object that points to the input stream.

Usage

To read a line of text using cin.getline(), follow these steps:

  1. Declare a character array to Store text.
  2. Call cin.getline() on the cin object, passing the character array and the maximum number of characters.
  3. The terminating character '\0' is automatically added to the end of the read text.

Example

<code class="cpp">char name[50];

// 从用户读取姓名
cin.getline(name, 50);

cout << "Hello, " << name << "!" << endl;</code>
Copy after login

Note

  • cin.getline() will skip any preceding Set spaces and tabs.
  • If the length of the text read exceeds the specified maximum number of characters, the buffer will be truncated.
  • If the user enters a blank line, cin.getline() will not store any text.
  • Do not use cin.getline() to read binary data.

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

Related labels:
c++
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template