Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to terminate a program with Ctrl-D?

Tags:

c++

exit-code

I am trying to write a simple program that simulates a calculator. I would like the program to exit or turn-off when the Ctrl+D keystroke is made. I searched through stackoverflow and saw other examples of Ctrl+C or Ctrl+A but the examples are in java and C.

for C:

(scanf("%lf", &var);

for java, a SIGINT is raised when Ctrl+Z is pressed.

signal(SIGINT,leave);  
    for(;;) getchar();

I am wondering what can I do for Ctrl+D in C++...

Thanks everyone!

like image 835
Ken Avatar asked Dec 30 '10 14:12

Ken


People also ask

How do you end a program immediately?

The exit() function is used to terminate a process or function calling immediately in the program. It means any open file or function belonging to the process is closed immediately as the exit() function occurred in the program.

What is used to terminate a program?

The exit function is used to exit or terminate the program.

What is Ctrl D in C?

Beginner at C/C++, Php, Java, Jquery, Mysql & Front-end Web Developer Author has 118 answers and 238.7K answer views 5y. Ctrl+D (^D) means end of file. It only works at the beginning of a line (I'm simplifying a little), and has no effect if the program isn't reading input from the terminal.

Which command terminate the execution of a program?

Then we hit Ctrl+C to terminate the execution.


2 Answers

Ctrl+D will cause the stdin file descriptor to return end-of-file. Any input-reading function will reflect this, and you can then exit the program when you reach end-of-file. By the way, the C example should work verbatim in C++, though it may not be the most idiomatic C++.

Is this homework, by the way? If so, please be sure to tag it as such.

like image 153
Will Robinson Avatar answered Oct 18 '22 17:10

Will Robinson


If you need to terminate with Ctrl-D while reading input.

 while ( std::cin ) // Ctrl-D will terminate the loop
{
  ...
}
like image 3
ytobi Avatar answered Oct 18 '22 17:10

ytobi