federico-busato / Modern-CPP-Programming

Modern C++ Programming Course (C++03/11/14/17/20/23/26)
https://federico-busato.github.io/Modern-CPP-Programming/
11.91k stars 798 forks source link

Extra empty line is processed in "I/O Stream - Example 1" #85

Closed eugenefil closed 6 months ago

eugenefil commented 6 months ago

On p.14 of file 16.Utilities.pdf under title "I/O Stream - Example 1" the line-by-line reading code will process extra empty line if either:

The fix is basically described in the reading-files-in-c-using-ifstream link provided later on p.16:

     std::string str;
-    while (fin.good()) {
-        std::getline(fin, str);
+    while (std::getline(fin, str)) {
         std::cout << str << "\n";

Or even shorter:

-    std::string str;
-    while (fin.good()) {
-        std::getline(fin, str);
+    for (std::string str; std::getline(fin, str);) {
         std::cout << str << "\n";

while (getline) won't execute body if nothing was read, because getline sets failbit on the returned stream in this case. And with the failbit set, the stream, when cast to bool, evaluates to false.

federico-busato commented 6 months ago

thanks! The link that you added provides so many insights about the topic. I added it at the end of the page

eugenefil commented 6 months ago

It really does. Note, you've provided that same link also on p.16 "I/O Stream -Check the End of a File", I found it there. Now there are 2 identical links: on p.14 (new) and on p.16 (old). Probably p.14 is really a better place for it, but it's up to you.

federico-busato commented 6 months ago

thanks!