Question

Somewhere back in time I did some C and C++ in college, but I didn't get to many attention to C++. Now I wish to pay some attention to C++ but when I'm using the getch() function, I get the warning from below.

Warning C4996: 'getch': The POSIX name for this item is deprecated. Instead, use the ISO C++ conformant name: _getch. See online help for details.

Now, I'm using VS 2005 express, and I don't know what to do about this warning. I need to use getch() after I printf() an error message or something else which require a key hit.

Can you help me with that?

Was it helpful?

Solution

Microsoft decided to mark the name without underscore deprecated, because those names are reserved for the programmer to choose. Implementation specific extensions should use names starting with an underscore in the global namespace if they want to adhere to the C or C++ Standard - or they should mark themselves as a combined Standard compliant environment, such as POSIX/ANSI/ISO C, where such a function then corresponds to one of those Standards.

Read this answer about getcwd() too, for an explanation by P. J. Plauger, who knows stuff very well, of course.

If you are only interested to wait for some keys typed by the user, there really is no reason not to use getchar. But sometimes it's just more practical and convenient to the user to use _getch and friends. However, those are not specified by the C or C++ Standard and will thus limit the portability of your program. Keep that in mind.

OTHER TIPS

If you're into C++, why printf and getch? Consider using cout and cin.get instead.

use _getch() instead of getch()

Why do you need this? Why not use getchar() if you need to capture a single character?

As the error says, the name getch() is deprecated (as that was a Microsoft-specific extension), and _getch() is recommended instead. I'm not sure where POSIX comes into it; POSIX does not define getch(), but instead includes getchar() as specified by the ISO C standard (page 298, draft linked to because final standard is not free). The solution would be to do as suggested and use _getch(), or use the standard C getchar().

you can use "std::getc(stdin);". It works like 'getch();' in my programs. I think It's a good alternative for 'getch()' If I'm wrong, tell me.

#include <cstdio>

switch (std::getc(stdin)) {
    case 'a':   cout << 'a' << endl ; break;
    case 'b':   cout << 'b' << endl ; break;
    default:    cout << '$' << endl; break;
}

It outputs 'a' if you input 'a' on console.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top