GETLINE()

The getline() function is used to read an entire line of text, including spaces, from an input stream into a std::string variable. It works with any input stream, such as std::cin for user input or std::ifstream for reading from a file. Unlike the >> extraction operator, which stops reading at whitespace, getline() continues until it encounters a newline character (\n) or the end of the file (EOF). This makes it ideal for reading input that may contain spaces, such as full names, sentences, or lines of text in a file.

When reading from a file using std::getline(std::ifstream& is, std::string& str), the function will read one line at a time from the file, discarding the newline character and storing the content in the string. getline() is specifically designed for reading text data, not numeric types, so it is particularly useful for processing lines of text, whether from user input or files, where the content may include spaces or other non-delimited characters.

getline(inputFile, line);

 * inputFile: The ifstream object representing the open file.
 * line: A string where each line from the file will be stored.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
    ifstream inputFile("data.txt");  // Open the file for reading

    if (inputFile.is_open()) {  // Check if the file opened successfully
        string line;
        
        // Read the file line by line
        while (getline(inputFile, line)) {
            cout << "Read line: " << line << endl;  // Print each line to the console
            // You can process the 'line' string here (e.g., extract data from it)
        }

        inputFile.close();  // Close the file
        cout << "File read successfully.\n";  // Confirmation message
    } else {
        cout << "Unable to open the file.\n";  // If the file couldn't be opened
    }

    return 0;
}

Last updated