Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fgets equivalent in C++

Tags:

c++

fgets

What is the C++ equivalent to the C function fgets?

I have looked at getline from ifstream, but when it comes to an end of line character, '\n', it terminates at and discards it. I am looking for a function that just terminates at the end line character but adds the end of line character to the char array.

like image 945
mitchell Avatar asked Feb 18 '26 15:02

mitchell


1 Answers

You can still use std::getline(); just append the newline character yourself. For example,

std::ifstream fs("filename.txt");
std::string s;
std::getline(fs, s);

// Make sure we didn't reach the end or fail before reading the delimiter:
if (fs)
    s.push_back('\n');
like image 141
James McNellis Avatar answered Feb 21 '26 04:02

James McNellis