Search code examples
cescapinguser-inputctrl

Exiting a program when user enters Ctrl+d in C


I am currently working on an assignment for class in which we have to write a program that takes user input from the command line.

The program should continue to take input from the user until a Ctrl+d character is written on its own line.

For example:

%./test

  • this is some text
  • this is a new line
  • ctrl+d

The program would stop after the last line (the '-' characters are just to show the user that they are still entering text).

So far I have this:

char c;

printf("- ");

while (c != EOF) {
    scanf(" %c", &c);
    printf("- ");
}

But when i type ctrl+d on execution it doesn't exit, any help would be much appreciated.

Also I would like this to work on my mac, so if anyone could shed light on if there is a different way to do this there (as cmd+d just splits the terminal window), that would also be much appreciated.

Thanks in advance!


Solution

  • Here is an easy solution to your problem:

    #include<stdio.h>
    
    main()
    {
    
       char c;
    
        int flag=0;
    
    printf("- ");
    
    while (flag != EOF) {
        flag = scanf(" %c", &c);
        printf("- ");
    
    }
    return 0;
    }
    

    using Scanf for multiple key buttons make it harder to catch. Instead of scanf assignment you should use the resulting of scanf which will give you the proper EOF result.

    Also

    In more tricky cases where you need multiple keys but without already prepared thing like EOF. You can try to simulate scanf loops to check if lets say ctrl key is being followed by d or a d following the ctrl. Because user does either ctrl+d or d+ctrl and you will be able to catch it with this loop, to make it look exactly like this example above. I know it is just a very sloppy solution but it does work.

    Sorry I got nothing for your MAC problem cause I do not have one to test it with.

    Good luck