using getch() to hold command prompt open Visual C

2019-06-08 05:29发布

Im currently learning c++ from a book called 'Ivor Hortons Beginning Visual c++ 2010'.

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.

Is this a vagary of windows 7 and will it cause problems further down the line? 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 :)

4条回答
\"骚年 ilove
2楼-- · 2019-06-08 05:32

Use _getch() in place of getch()

查看更多
欢心
3楼-- · 2019-06-08 05:37

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. This is normal behavior and should continue to work that way until Windows is a distant memory.

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.

查看更多
霸刀☆藐视天下
4楼-- · 2019-06-08 05:44

getch() is not operating system specific, but it is not directly portable. The preferred method for doing this in C++ is to use std::cin.get();.

The main function can return 0 implicitly (you don't need to actually have that code, see below).

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

See this question for more details about the implicit return 0 from main.

查看更多
冷血范
5楼-- · 2019-06-08 05:53

First, getch() isn't a standard C or C++ function. Even under Windows, I think its use is deprecated; its semantics go back to CP/M and early 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).

查看更多
登录 后发表回答