简体   繁体   English

使用getch()来保持命令提示符打开Visual C ++ 2010

[英]using getch() to hold command prompt open Visual C++ 2010

Im currently learning c++ from a book called 'Ivor Hortons Beginning Visual c++ 2010'. 我目前正在从一本名为“Ivor Hortons Beginning Visual c ++ 2010”的书中学习c ++。

In all the examples i've attempted so far I've had to use getch() to hold open the command prompt, and sometimes remove the return 0 statement from the end of the main method. 在我迄今尝试的所有示例中,我必须使用getch()来保持打开命令提示符,有时会从main方法的末尾删除return 0语句。

Is this a vagary of windows 7 and will it cause problems further down the line? 这是Windows 7的变幻莫测,是否会导致问题进一步发展? It's no problem doing this at the moment but since this is not included in the book I was wondering if it might be something I've set up wrong. 这样做是没有问题的,但由于这不包括在书中,我想知道是否可能是我设置错了。

Many Thanks :) 非常感谢 :)

使用_getch()代替getch()

getch() is not operating system specific, but it is not directly portable. getch()不是特定于操作系统的,但它不是直接可移植的。 The preferred method for doing this in C++ is to use std::cin.get(); C++执行此操作的首选方法是使用std::cin.get(); .

The main function can return 0 implicitly (you don't need to actually have that code, see below). main函数可以隐式return 0 (您不需要实际拥有该代码,请参阅下文)。

int main()
{
   // valid, return 0 implied.
}

See this question for more details about the implicit return 0 from main . 有关从main隐式return 0更多详细信息,请参阅此问题

When a program ends, any resources created by that program including the terminal window will be released. 当程序结束时,该程序创建的任何资源(包括终端窗口)都将被释放。 By using getch you prevent the program from ending. 通过使用getch可以防止程序结束。 This is normal behavior and should continue to work that way until Windows is a distant memory. 这是正常行为,应该继续以这种方式工作,直到Windows是一个遥远的记忆。

If you start the program from within an already existing command window, the window will not close because it wasn't created by the program. 如果从现有命令窗口中启动程序,则窗口不会关闭,因为它不是由程序创建的。

First, getch() isn't a standard C or C++ function. 首先, getch()不是标准的C或C ++函数。 Even under Windows, I think its use is deprecated; 即使在Windows下,我认为它的使用已被弃用; its semantics go back to CP/M and early MS-DOS. 它的语义可以追溯到CP / M和早期的MS-DOS。

Secondly, it really isn't necessary, at least not for console apps (and I don't think it's available for non-console apps). 其次,它确实没有必要,至少不适用于控制台应用程序(我认为它不适用于非控制台应用程序)。 If you're running the program from a console window, the window stays open. 如果从控制台窗口运行程序,则窗口保持打开状态。 And if you're running it from Visual Studios, it's trivial to set a breakpoint on the return statement, which blocks the program, and keeps the window open (although there's really no reason for the IDE to close it just because your program has terminated). 如果你是从Visual Studios运行它,那么在return语句上设置一个断点是很简单的,它会阻止程序,并保持窗口打开(尽管IDE没有理由因为你的程序已经终止而关闭它)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM