rdu-cpp

杨柳不折
随笔 - 13, 文章 - 0, 评论 - 4, 引用 - 0
数据加载中……

Console Closing Down

Zolaboony (1) May 19, 2008 at 5:30am
Hi, i am new to C++ and have just written my "Hello World" program. It worked all right but the console/cmd closes down instantly. If you tell me why it is closing down it would be very helpful.

Duoas (1617) May 19, 2008 at 5:40am
It is because your IDE is too stupid to know that a console application run from the IDE should have an automatic pause at the end.

Add the following to the end of your main() function to fix it:
1
2
3
4
5
6
7
  ...
                        std::cout << "Press ENTER to continue...";
                        std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
                        return 0;
                        }

You'll need to #include <limits>

Enjoy.

ropez (312) May 25, 2008 at 1:44pm
First I would search for the setting in my IDE that says "Keep console window open after program terminates".

If I didn't find it, I'd send a request for it to be included in the next version.

In the meantime: All the suggestions so far assumes that the program reach the end of main. Neither of you considered exceptions, or something like this in main:
1
2
if (somethingFailed())
                        return SOME_ERROR_CODE;


I suggest creating this small tool:
1
2
3
4
5
6
7
8
class KeepRunning {
                        public:
                        ~KeepRunning() {
                        // Whatever code you prefer to keep the program running, e.g.
                        system("pause"); // "Press enter"
                        sleep(5); // Wait 5 seconds
                        }
                        };


In your main function:

1
2
3
4
5
6
int main() {
                        KeepRunning kr;
                        // code
                        } // Program stops here 


This way the program must keep the console open, even if it doesn't reach the end of main.

BTW: Of course, remember to remove this code before the program is "released".

posted on 2009-01-20 17:19 rdu 阅读(337) 评论(1)  编辑 收藏 引用 所属分类: 论坛拾珠

评论

# re: Console Closing Down  回复  更多评论   

thread@http://www.cplusplus.com/forum/beginner/1988/
2009-01-20 17:19 | rdu

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理