-3

I have an input file "abc.txt" which contains characters seperated by ',' in every line. While trying to read the file line by line using ifstream, its unable to read the file and I am getting the output on console as "Cannot open input file.". What am I doing wrong? The code:-

void EnterFiles(string filename, int index)
{
    string line;
    vector<string> f1,f2;

    std::ifstream f;

    //prepare f to throw if failbit gets set

    std::ios_base::iostate exceptionMask = f.exceptions() | std::ios::failbit;
    f.exceptions(exceptionMask);
    try
    {
        f.open(filename);
    }
    catch (std::ios_base::failure& e)
    {
        std::cerr << e.what() << '\n';
    }
    if (!f)
    {
        cout << "Cannot open input file.\n";
    }
    while (getline(f,line) )
    {   
        if (index == 0)
        {
            f1.push_back(line);
            cout << line << endl;
        }
        else
        {
            f2.push_back(line);
            cout << line << endl;
        }
    }
    f.close();
}

enter image description here

Blacktempel
  • 3,935
  • 3
  • 29
  • 53

1 Answers1

0

If condition is satisfied every time, thus skipping else part.

provide full or qualified file path (Sometimes it creates problem !!), Also, include file (if not !!).

Following is an examples similar to your code, which you refer, (It is checked by me works like a charm in Linux)

http://cpp-tutorial.cpp4u.com/STL_ifstream.html

Hope, this answer might be of help.

Neel Shah
  • 12
  • 3