0
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
    //reading the text file
    ifstream inputFile("testfile1.txt");
    inputFile.open("testfile1.txt");
    while(!inputFile.eof())
    //eof till end of file, reads the txt till end of file
    {
        string str;
        getline(inputFile,str);
        cout <<str<< endl;

    }
        inputFile.close();

    return 0;
}

// The problem that i am having is that it doesn not read the file or anything in it. Doing nothing it says Program ended with exit code: 0. Could anyone check the mistake in the code

Ashim
  • 631
  • 1
  • 8
  • 20
  • Unrelated: you opened the file twice ? – WhozCraig Nov 06 '16 at 03:26
  • 2
    No, it's very much related. Opening the same file twice is the bug here. The second `open()` fails, and sets the `fail` bit on the file stream. The second bug here is the popular [while eof bug](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong). – Sam Varshavchik Nov 06 '16 at 03:33
  • @SamVarshavchik apparently the code has morphed, because a few minutes ago the logic in the loop conditional was the contra-positive of what it is now. Go figure. – WhozCraig Nov 06 '16 at 03:35
  • Well, even though it's morphed it is still wrong. But that's just one of the two bugs. – Sam Varshavchik Nov 06 '16 at 03:36
  • Is this the **real** code you are asking about? Since you have changed it significantly since initially posting it, that's a valid question. – IInspectable Nov 06 '16 at 03:37
  • Yeah, I was so focused on the other two bugs, I didn't think about the first. Good catch. Post that up so I can uptick it =P. – WhozCraig Nov 06 '16 at 03:37
  • @SamVarshavchik Could you be specific why is it wrong ? while(!inputFile.eof()) is so that all the elements in the .txt is read until the end of the file. It is not for opening the file. I dont see how is it opened twice? – Ashim Nov 06 '16 at 03:40
  • @user45524 Throw out the `.open` call. You already opened the file with the constructor. After that, [heed the link Sam provided](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – WhozCraig Nov 06 '16 at 03:43

3 Answers3

1

First Bug: You are opening the input file twice. Per the C++ standard, regarding the behavior of your second open request (the direct call to the open member):

C++11 § 27.9.1.9 [ifstream.members/3]

void open(const char* s, ios_base::openmode mode = ios_base::in);

Effects: Calls rdbuf()->open(s, mode | ios_base::in). If that function does not return a null pointer calls clear(), otherwise calls setstate(failbit) (which may throw ios_base::failure (27.5.5.4)).

which therefore asks the question, what does rdbuf()->open(...) do ? Well, a std::ifstream uses a filebuf for it's buffering, and once again, per the standard:

C++11 §27.9.1.4 [filebuf.members/2]

basic_filebuf<charT,traits>* open(const char* s, ios_base::openmode mode);

Effects: If is_open() != false, returns a null pointer. Otherwise, initializes the filebuf as required. ...

In short, your double-open is putting your stream into a fail-state, which means all data-related operations with it are going to fail outright from that point on.


Second Bug: Improper use of .eof in a loop conditional expression. you'll run into this once you fix the first bug. The reasons this is not being done correctly are explained in the following question far better than I can explain it here.

Why is iostream::eof inside a loop condition considered wrong?

Suffice it to say, check your IO operations, not just the eof-state of the stream. Get into that habit and stick with it.

Fixing both, your code can literally be reduced to simply this:

#include <iostream>
#include <fstream>
#include <string>

int main()
{
    std::ifstream inputFile("testfile1.txt");
    std::string str;
    while (std::getline(inputFile, str))
        std::cout << str << std::endl;
}

Obviously if you're shooting for more robust code, you probably want to perform some error handling in there, something like:

#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>

int main()
{
    std::ifstream inputFile("testfile1.txt");
    if (!inputFile)
    {
        std::cerr << "Failed to open file\n";
        return EXIT_FAILURE;
    }

    std::string str;
    while (std::getline(inputFile, str))
        std::cout << str << std::endl;
}
WhozCraig
  • 59,130
  • 9
  • 69
  • 128
0

This is the correct way to read a file according to this article! The problem in your code it seems that you are using an IDE and it cannot find the path you are giving to ifstream so try to give a full path to the file. Hope it can help u.

string line;
ifstream f("/YOUPARTH/testfile1.txt");
if (!f.is_open())
    perror("error while opening file");
while(getline(f, line)) {
   cout << line << endl;
}
if (f.bad())
    perror("error while reading file");
return 0;
-1

Translate the while statement: "While inputFile is at End Of File" .. you want the negation of that.

a_caban
  • 58
  • 4
  • sorry i actually had (!inputfile.eof) but it still does not do anything. Could there be a problem in reading the file ? – Ashim Nov 06 '16 at 03:31