Ok Guys I need some help with a small nigglying problem I have traditionally used
the following code to check for a keypress when using the console and in msdos thats how far back Ive been using getch() but need to do something similar to this in C++ with cin and iostream.h

see:

#include <conio.h>
char c;
printf("Press any key to continue..");
c = getch();

Is there some easy way to do the same in C++ with iostream.h and cin ?

any help would be greatly appreciated.

Edited 6 Years Ago by technology: n/a

heya there are two options here for you,

you can declare a character and read with cin or tell cin that you want only a character such as below

char myChar;
cin>>myChar;//cin sees a char variable so reads only a char

//or 

myChar = cin.get(); //the same as getchar but using cin

This answers your question i hope

My huge appreciation for this as this has been annoying the hell out of me for a while. Anyhow If I was with you I buy ya a beer for that thanks all.

In addition you have:

(IOSTREAM HEADER)
getline( istream& is, string& str )

string mystring;
getline(cin, mystring);

(STDIO HEADER)
scanf( const char * format, ... )

string mystring;
scanf("%s", mystring);

(WINDOWS INPUT)

//....
LRESULT CALLBACK WindowProc(HWND hWnd, UINT Message, WPARAM wParam, LPARAM lParam)
{
    switch(message)
    {
        case WM_DESTROY: break;
		case WM_ACTIVATEAPP: break;

		case WM_KEYDOWN:
			{
			        int virtual_key = (int)wParam;
				int key_bits = (int)lParam;
				switch(virtual_key)
				{
				case VK_ESCAPE:break;

				case VK_RETURN:break;

				//case VK_....
				}
			}
			break;
    }

    return DefWindowProc (hWnd, Message, wParam, lParam);
}

(DIRECTX)

void Input()
{
    static BYTE Keys[256];

    GetKeys(&Keys[0]);

	ZeroMemory(&KeyboardInput, sizeof(KeyboardInput));

	for( int i = 0; i <= 256; i++){
		KeyboardInput.Keys[i] = Keys[i];
	}

	if(Keys[DIK_ESCAPE]) //....
	if(Keys[DIK_F]) //....
	if(Keys[DIK_O]) //....
	if(Keys[DIK_O]) //....
}

Edited 6 Years Ago by ShadowScripter: n/a

Not a valid solution -- unless you want the ability to crash at will. See this. And since when does scanf() work on C++ Strings?

Whopsie, I was copy - pasting at this point. However, I did turn to a reference before giving the example, where the given reference actually corrects my mistake as well, but thanks for pointing it out.

I agree with you, it's a bad function. It does more work, alot more than is needed. It's also quite confusing at first, if you don't know what commands to put in it.
With that being said, it still does its job. For a beginner, that's really all he needs to know.

As for the apparent buffer overflow, there is always a risk that some memory will be overwritten or will segfault because of bad programming; human nature. Just look at mine :$

Edited 6 Years Ago by ShadowScripter: n/a

This article has been dead for over six months. Start a new discussion instead.