0

I know there are similar questions about EOF and CTRL+D, but I have a more specific question. The way I understand it, CTRL+D signals the end of STDIN and is handled by the computer and not the running application. However, I need to provide feedback to the user of my program on an EOF character typed via (CTRL+D) or contained within an input file containing commands. How would I do this?

I have included my simple code on how I thought to do it, but it doesn't work for obvious reasons:

#include <iostream>
#include <string>
using namespace std;

int input()
{
    string cmdstring;
    cin >> cmdstring;
    if (cmdstring == "bye") //Exit on "bye" command
    {
        return 1;
    }
    else if (cmdstring == "^D") //Exit on EOF character CTRL+D
    {
        return 2;
    }
    else //Continue shell prompt
    {
        return 0;
    }
}

I'm trying to write my own shell, and I want to provide an exit status when the shell quits. Thank you very much!

Edit: I changed it to cin.eof(), but it still doesn't work.

else if (cin.eof()) //Exit on EOF character CTRL+D
{
    return 2;
}

Additionally, I forgot to mention that this code is a function running within a loop, so the user is continually prompted until they supply "bye" or an EOF character is read.

int exitstatus = 0; //Tracks exit code status
do {
    exitstatus = input();
} while (exitstatus == 0);
mallux
  • 77
  • 1
  • 2
  • 6
  • I would think `if(cin.eof())` should do it. – Galik Nov 03 '14 at 21:24
  • I didn't know about that! However, it didn't seem to work either sadly. It doesn't seem to catch the EOF character, but it places a "^D" character in my terminal, so that's why I had it like that initially. – mallux Nov 03 '14 at 21:32
  • There is no "^D" character. The shell intercepts the "^D" character and sets the EOF state on `stdin` as a result. – Galik Nov 03 '14 at 21:49
  • I updated the question with some more information to help out. :) – mallux Nov 03 '14 at 21:50
  • I am surprised checking `eof()` didn't work for you I believe that's what effect pressing `Ctrl-D` is supposed to have. – Galik Nov 03 '14 at 21:55

1 Answers1

1

There is no "^D" character passed to the application. The shell intercepts the "^D" character and closes the stream causing the application to register no more input. As a result of that the I/O system sets the EOF state on stdin.

This code works for me:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string cmdstring;

    cin >> cmdstring;

    if(cmdstring == "bye") //Exit on "bye" command
    {
        return 1;
    }
    else if(cmdstring == "^D") //Exit on EOF character CTRL+D
    {
        return 2;
    }
    else if(cin.eof()) // pressing Ctrl-D should trigger this
    {
        return 3;
    }
    return 0;
}

Pressing Ctrl-D should return error code 3

Galik
  • 47,303
  • 4
  • 80
  • 117