When std::istream::getline
has read 100-1 characters (without finding a newline,\n
), it will set the failbit
on the stream. This prevents further reading on the stream (unless you reset that state). It does however not set eofbit
so you are now in a bit of a pickle. The failbit
prevents further reading, and eof()
returns false
, because eofbit
is not set - it will therefore loop indefinitely.
If at least one of the lines in Story.txt
is longer than 99 char
s, the above is what will happen.
The easiest way out is to use a std::string
and std::getline
instead:
#include <cerrno>
#include <cstring>
#include <fstream>
#include <iostream>
#include <string>
int main() {
std::ifstream jin("Story.txt");
if(!jin) {
std::cerr << "File not opened: " << std::strerror(errno) << std::endl;
return 1;
}
std::string a;
while(std::getline(jin, a)) {
std::cout << a << '\n';
}
return 0;
}
If you really do not want to use std::getline
and std::string
, you can, but it's much harder:
#include <cerrno>
#include <cstring>
#include <fstream>
#include <iostream>
int main() {
std::ifstream jin("Story.txt");
if(!jin) {
std::cerr << "File not opened: " << std::strerror(errno) << std::endl;
return 1;
}
char a[100];
while(true) {
jin.getline(a, 100);
std::cout << a; // output what we got
if(jin) {
// got a complete line, add a newline to the output
std::cout << '\n';
} else {
// did not get a newline
if(jin.eof()) break; // oh, the end of the file, break out
// reset the failbit to continue reading the long line
jin.clear();
}
}
}