getfile() not reading anything C++

  c++, file-io, getline, io

I am trying to read words from a dictionary file whose filename is provided by the user. The program does open the file properly, but upon an attept to getline() the program sees nothing. I’ve had success with getline before but this is confusing me.

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

int main() 
{
    cout << "Filename: ";
    string dictName;
    cin >> dictName;  
    ifstream dictionary(dictName, ios::in);
    dictionary.open(dictName);
    if(dictionary.is_open())
    {
        int numLines = 0;
        cout << "nnReading the dictionary...n";
        
        string word;
        while(dictionary.peek() != EOF)
        {
            getline(dictionary, word);
            cout << word <<endl;
            numLines++;
        }
        
        dictionary.close();
        
        cout << "The dictionary contains ";
        cout << numLines;
        cout << " words.n";
    }
    else
    {
        cout << "Cannot open Dictionary file...";
    }
    
    return 0;
}

However it does not output anything from the file, I’ve tried with many files and I cant get any to work. It does output the strings (Reading the Dictionary…) so I know the file is opening.

I may have made a few errors in this simplified version of my full code.

Source: Windows Questions C++

2 thoughts on - getfile() not reading anything C++

LEAVE A COMMENT