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."

Step 1

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

include

using namespace std;

int main(){

return 0; }

Step 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; }

Step 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; }

×