In C++ file handling, which of the following correctly reads a line of text…

2025

In C++ file handling, which of the following correctly reads a line of text from a file into a string variable?

  1. A.

    file.readLine(str);

  2. B.

    read(file, str);

  3. C.

    getline(file, str);

  4. D.

    file.getline(str);

Attempted by 90 students.

Show answer & explanation

Correct answer: C

In C++, the getline() function is commonly used to read a complete line of text from a file into a string variable.

Example:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
   ifstream file("data.txt");
   string str;

   getline(file, str);

   cout << str;
}

Here:

file → input file stream
str → string variable
getline(file, str) → reads one entire line from the file

This is the standard and correct approach for line-based text input in C++.

Explore the full course: Rssb Senior Computer Instructor