Search code examples
c++unixctrl

I am trying to end my C++ program when the user presses 'Ctrl-D'


my program has read in a large file of words (a dictionary) and inserted them all into a hash table. I am prompting the user to lookup a word and I want them to be able to terminate the program by pressing Ctrl-D. This is what I have tried but when I press Ctrl-D it just gets stuck in a loop printing out what I have in the else statement. I am using Unix. I have attempted looking this up on this website and nothing was working that I was trying hence why I am asking my own question. Any thoughts? PS. The transform is to make the user input all uppercase to match the file I am reading from.

void query(){
            bool done = false;
            string lookupWord;
            while(!done){
                    cout << "Type a word to lookup or type ctrl-D to quit: ";
                    cin >> lookupWord;
                    if(atoi(lookupWord.c_str()) == EOF)
                            done = true;
                    else{
                            transform(lookupWord.begin(), lookupWord.end(), lookupWord.begin(), ::toupper);
                            cout << endl << "Word: " << lookupWord << endl;
                            cout << endl << "Definition: " << myDict.lookup(lookupWord) << endl << endl;
                    }
            }
    }

Solution

  • atoi(lookupWord.c_str()) == EOF
    

    This doesn't do what you think it does. This checks the return value of atoi() and compares it to EOF. EOF is typically defined as -1. So, the code ends up setting done only when -1 is typed in. Which is not what you want.

    std::istream has a convenient operator bool that tests whether the file stream is in a good state. So, all that really needs to be done is:

    if (cin >> lookupWord)
    {
        // Your existing code is here
    }
    else
    {
        done=true;
    }