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?
- A.
file.readLine(str);
- B.
read(file, str);
- C.
getline(file, str);
- 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++.