How is the getLine function used in C++?

In C++, the getline function is used to read a line of data from an input stream. It is commonly used in several different ways.

  1. Read a line of data from the standard input stream (cin).
#include <iostream>
#include <string>

int main() {
    std::string line;
    std::getline(std::cin, line);
    std::cout << "输入的行数据为:" << line << std::endl;
    return 0;
}
  1. Read a line of data from a file stream.
#include <iostream>
#include <fstream>
#include <string>

int main() {
    std::ifstream file("file.txt");
    std::string line;
    if (file.is_open()) {
        std::getline(file, line);
        std::cout << "文件中的第一行数据为:" << line << std::endl;
        file.close();
    } else {
        std::cout << "无法打开文件" << std::endl;
    }
    return 0;
}
  1. Specify a custom delimiter (default is ‘\n’):
#include <iostream>
#include <string>

int main() {
    std::string line;
    std::getline(std::cin, line, ',');
    std::cout << "输入的以逗号分隔的数据为:" << line << std::endl;
    return 0;
}

It is important to note that the getline function reads a line of data until it encounters a delimiter (by default, a newline character ‘\n’). It removes the delimiter from the input stream and stores the read data in the specified string variable.

bannerAds