How to terminate a program with Ctrl-D?

試著忘記壹切 提交于 2019-12-01 20:24:57

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

 while ( std::cin ) // Ctrl-D will terminate the loop
{
  ...
}
Will Robinson

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.

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.

J. C. Salomon

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.

Lou Franco

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!