How to Check for Ctrl-D in C++

by G.S. Jackson

The C++ programming language is useful for programming desktop applications and operating systems. C++ works well as a tool when speed and low-level hardware management is required. When receiving user input from a terminal application, the input command for C++ will halt when receiving an "EOF" signal. Using this, you can check whether or not a user clicks the key combination of "Ctrl" and "D."

1

Set up a C++ program that can handle user input and output. This includes importing the required libraries in the pre-processor:

include <iostream>

using namespace std;

int main(){

return 0; }

2

Set up an infinite loop that will accept user input and place it into a variable, using the "cin" function and a while loop:

int main(){

int x = 0; while (cin >> x){

}

return 0; }

3

Check for "EOF." The "cin" function will return a false value if it receives an end of file signal, either through the "EOF" symbol or through the user pressing "Ctrl" and "D." You can check for "EOF" and take appropriate action:

int main(){

int y = 0;

while(cin >> y ){ cout << y; }

if (cin.eof()){ //checks for Control-D / EOF cout << "yup"; priants only if cin hits EOF through Control-D }

return 0; }

Items you will need

About the Author

G.S. Jackson specializes in topics related to literature, computers and technology. He holds a Bachelor of Arts in English and computer science from Southern Illinois University Edwardsville.