📜  c++ getline - C++ (1)

📅  最后修改于: 2023-12-03 15:13:54.262000             🧑  作者: Mango

c++ getline - C++

The getline function in C++ is used for reading input from a stream until a specified delimiter is encountered. It is commonly used to read a line of text from the input stream.

Syntax

The getline function has the following syntax:

istream& getline (istream& is, string& str, char delim);

Where:

  • is: The input stream object from which to read the input.
  • str: The string object where the input will be stored.
  • delim: The delimiter character that specifies when to stop reading.
Return Value

The getline function returns the input stream object is after reading the line of text and storing it in the string str. This allows for chaining multiple input operations.

If the specified delimiter is encountered before any characters are read, getline considers the input to be an empty string and stores it in str. If an error occurs during the input operation, the failbit of the input stream is set and the function returns the input stream object with the failbit set.

Example

Here is an example that demonstrates the usage of getline:

#include <iostream>
#include <string>

int main() {
    std::string input;

    // Read a line of text from the standard input until a newline character is encountered
    std::cout << "Enter a line of text: ";
    std::getline(std::cin, input);

    // Print the input
    std::cout << "You entered: " << input << std::endl;

    return 0;
}

In this example, the getline function is used to read a line of text from the standard input until a newline character is encountered. The input is then printed back to the console.

Markdown code block
istream& getline (istream& is, string& str, char delim);
#include <iostream>
#include <string>

int main() {
    std::string input;

    std::cout << "Enter a line of text: ";
    std::getline(std::cin, input);

    std::cout << "You entered: " << input << std::endl;

    return 0;
}