0

Visual C ++を初めて使用した場合(この言語も初めて)-経験豊富なC#...したがって、VisualStudioで開始した最初のコンソールアプリがあります。

#include "stdafx.h"
#include <iostream>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    int i;

    cin >> i;

    return 0;
}

Enterキーを押しても、コンソールウィンドウ(つまりアプリケーション)が閉じないのはなぜですか?他の入力はありません-入力するだけです...

exit()さらに重要なのは、 Enterキーを押しただけで、アプリを適切に終了させる(使用したくない)にはどうすればよいですか?

4

1 に答える 1

2

std::cin awaits one non-empty string from you and then tries to convert this string to integer.

When you press Enter std::cin only gets an empty string and continues to wait for some valid input. This is by design. std::cin is not meant for emulating other interaction.

To terminate the app on keypress, you have to use OS-specific facilities to read keyboard presses.

This is the kbhit() function from "conio.h" on DOS/console Windows and the termio functions on POSIX systems.

From your source I can conclude that you use the MSVC++ compiler, so try replacing

std::cin >> i

by

while(!kbhit()) {}

Do not forget to add the

#include <conio.h>

and remember this is a Windows-specific solution.

于 2012-05-25T23:37:31.217 に答える