-2

I'm working on a project where I have to read a dictionary from a text file using command line redirection (ie. ./myprog myargs < in.txt)

I then pass cin to a function to construct a dictionary object.

int main(int argc, char *argv[]) {

Dictionary all_words(std::cin);
Dictionary solution;
std::deque <Word> possible_additions;

std::cout << all_words[0].get_word() << " this is a word" << '\n';

opterr = true;
static struct option longopts[] = {
    { "stack",    no_argument,       nullptr,    's' },
    { "queue",    no_argument,       nullptr,    'q' },
    { "change",   no_argument,       nullptr,    'c' },
    { "swap",     no_argument,       nullptr,    'p' },

etc.

Dictionary::Dictionary(std::istream& is) {
char type;
int size;
std::string line;
int i = 0;

is >> type >> size;

words.reserve(size);

while (!is.eof()) {
    getline(is, line);

    if (type == 's') {
        if ((line.length() == 0 || line[0] == '/') &&
            (line.length() == 0 || line[1] == '/'))
        {
            continue;
        }

        else {
            std::cout << line << '\n';
            words.push_back(line);
            ++i;
        }
    }

My problem is that nothing is being added to the dictionary. However, if I initialize a dictionary with a ifstream of the file name, it works fine.

ie:

Dictionary a;
std::ifstream testFile;
testFile.open("simple-dict.txt");
Dictionary b(testFile);

works fine and builds the dictionary.

I didn't encounter this problem while using MSVS, but now that I'm using gcc it doesn't seem to work.

Thanks for any help!

Nate Neal
  • 1
  • 2
  • You must always directly test the return value of getline() and other input functions. You must not loop on eof(). See https://latedev.wordpress.com/2012/12/04/all-about-eof/ for why. –  Jan 26 '17 at 00:54
  • @NeilButterworth So if I understand correctly I should use while(getline(is, line)) instead of eof? – Nate Neal Jan 26 '17 at 01:04

1 Answers1

0

Looks like it was the eof(). Never realised the problems it could cause. Changing it to getline(is, line) fixed it

Nate Neal
  • 1
  • 2