How to terminate a program with Ctrl-D?

2019-02-26 09:31发布

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!

标签: c++ exit-code
5条回答
狗以群分
2楼-- · 2019-02-26 10:04

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.

查看更多
一夜七次
3楼-- · 2019-02-26 10:16

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

 while ( std::cin ) // Ctrl-D will terminate the loop
{
  ...
}
查看更多
别忘想泡老子
4楼-- · 2019-02-26 10:17

You could make life easier and scan for a keyword like "quit" or "exit". Last time I used a calculator, these words were not on the keypad.

Many simple calculator programs read the input as text terminated by a newline. They parse the text in memory, then spit out an answer.

Other more sophisticated calculator programs use windows and are event driven. Some use a button like "=" to signal end of input and start of calculation (doesn't work on RPN calculators).

These techniques remove the hassle of determining End Of Text input using a control character sequence and are more portable.

查看更多
手持菜刀,她持情操
5楼-- · 2019-02-26 10:22

Ctrl+D on Unixy platforms is EOF. If you are getting each char, you can check to see if you got EOF.

查看更多
Lonely孤独者°
6楼-- · 2019-02-26 10:30

Under Unix, the terminal will interpret Ctrl+D (on an empty line) as the end of input; further reads from stdin will return EOF, which you can watch for.

查看更多
登录 后发表回答