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?
asked May 2, 2009 at 14:53
Duncan BenoitDuncan Benoit
3,2278 gold badges28 silver badges26 bronze badges
5
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.
answered May 2, 2009 at 14:57
1
If you’re into C++, why printf
and getch
? Consider using cout
and cin.get
instead.
answered May 2, 2009 at 15:04
Eli BenderskyEli Bendersky
258k88 gold badges347 silver badges410 bronze badges
1
use _getch() instead of getch()
answered Apr 2, 2013 at 19:07
1
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()
.
answered May 2, 2009 at 15:05
Brian CampbellBrian Campbell
317k56 gold badges358 silver badges339 bronze badges
2
Why do you need this? Why not use getchar()
if you need to capture a single character?
answered May 2, 2009 at 14:56
dirkgentlydirkgently
107k16 gold badges129 silver badges187 bronze badges
2
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.
answered Feb 2, 2019 at 11:19
aariowaariow
761 silver badge9 bronze badges
mster-doc 16 / 16 / 12 Регистрация: 10.11.2012 Сообщений: 245 |
||||
1 |
||||
23.02.2016, 10:52. Показов 36127. Ответов 10 Метки нет (Все метки)
Здравствуйте. Не понимаю в чём ошибка. Кликните здесь для просмотра всего текста
Сообщение об ошибке:
__________________
0 |
3433 / 2812 / 1249 Регистрация: 29.01.2016 Сообщений: 9,426 |
|
23.02.2016, 11:04 |
2 |
Сообщение было отмечено Kerry_Jr как решение РешениеСтудия выдаёт? Добавлено через 6 минут Или, выше всех инклудов, прописать: #define _CRT_SECURE_NO_WARNINGS (для getch() не работает, нужно заменить на _getch()). Или, ниже всех инклудов, прописать: #pragma warning(disable : 4996)
3 |
3102 / 2587 / 1219 Регистрация: 14.05.2014 Сообщений: 7,231 Записей в блоге: 1 |
|
23.02.2016, 11:06 |
3 |
Сообщение было отмечено Kerry_Jr как решение Решение
‘getch’: The POSIX name for this item is deprecated. Instead, use the ISO C and C++ conformant name: _getch. Тут четко написано: Имя в POSIX-стиле для этой функции устарело. Вместо него используй
2 |
16 / 16 / 12 Регистрация: 10.11.2012 Сообщений: 245 |
|
23.02.2016, 11:25 [ТС] |
4 |
Хмм… (( Я перепробовал все вышеперечисленные варианты. Не получилось…
0 |
3433 / 2812 / 1249 Регистрация: 29.01.2016 Сообщений: 9,426 |
|
23.02.2016, 11:28 |
5 |
даже просто заменял на _getch(); не вышло… Все другие способы, именно для getch(), не действуют:
(для getch() не работает, нужно заменить на _getch()). Замена на _getch() должна работать. Студия какая?
0 |
3433 / 2812 / 1249 Регистрация: 29.01.2016 Сообщений: 9,426 |
|
23.02.2016, 11:31 |
6 |
… Миниатюры
1 |
3433 / 2812 / 1249 Регистрация: 29.01.2016 Сообщений: 9,426 |
|
23.02.2016, 11:33 |
7 |
int name() Это у тебя точка входа такая?
1 |
16 / 16 / 12 Регистрация: 10.11.2012 Сообщений: 245 |
|
23.02.2016, 11:39 [ТС] |
8 |
Я ранее буквально на прошлой неделе в этой же Visual Stodio 2015 использовал и там компилится без проблем. Я даже свойства проекта изменил как у того и всё ровно не работает.
0 |
3433 / 2812 / 1249 Регистрация: 29.01.2016 Сообщений: 9,426 |
|
23.02.2016, 11:44 |
9 |
Я ранее буквально на прошлой неделе в этой же Visual Stodio 2015 использовал Как там было на прошлой неделе — это один ты знаешь. На скринах (6 пост и здесь) — работа кода в 15 -й студии (Community). Миниатюры
1 |
mster-doc 16 / 16 / 12 Регистрация: 10.11.2012 Сообщений: 245 |
||||
23.02.2016, 11:44 [ТС] |
10 |
|||
Да. Всем спасибо. Кликните здесь для просмотра всего текста
Работает. Всем спасибо.
0 |
0 / 0 / 0 Регистрация: 21.06.2019 Сообщений: 1 |
|
21.06.2019, 12:31 |
11 |
Visual Studio 2017: вместо getche() идентично работает _gettche();
0 |
IT_Exp Эксперт 87844 / 49110 / 22898 Регистрация: 17.06.2006 Сообщений: 92,604 |
21.06.2019, 12:31 |
11 |
Learn why this error appears in your C++ code and how to solve it.
For newbies in C++ using modern tools may become a big headache, specially when the VS version of your school is pretty old and you have the latest version of VS at home. One of the most known exercises for students, is the famous hello world in this language. Playing with a console application, the exercise is simple, print «hello world» and keep the console open to see the printed message. According to the programming style of your teacher you may receive an example snippet using cout:
#include <iostream>
#include <conio.h>
using namespace std;
void main(void)
{
cout << "Hello World" << endl;
getch();
}
Or using printf
to print the text in the console:
#include <iostream>
#include <conio.h>
void main(void)
{
printf("Hello World");
getch();
}
Both scripts are totally valid and they use the getch method to keep the console open. They should work normally in the compilers of the school where VS is always outdated, however, if you use a modern compiler to compile any of the previous examples (using latest version of Visual Studio), you will face the exception. The problem is that the getch method is a non-standard function, and MS compilers have traditionally offered those under two names, but Microsoft decided to define the name without underscore deprecated, because those names are reserved for the programmer.
Solution
The most simple workaround for this issue is to use the _getch
method with an underscore as prefix:
#include <iostream>
#include <conio.h>
using namespace std;
void main(void)
{
cout << "Hello World" << endl;
// Use the getch method with a prefixed underscore
_getch();
}
This method works the same but won’t be recognized as deprecated. You can as well use the cin.get
method of the std namespace:
#include <iostream>
#include <conio.h>
using namespace std;
void main(void)
{
printf("Hello World");
// Allow the input of text in the command line
// this will keep the console open
cin.get();
}
Happy coding !
- Remove From My Forums
-
Question
-
I have been writing some code to a program that I wanted, which deals with multi-menu’s and sets in creating rooms customers
and deleting add and modifying on the fly. My problem persists in the function on the getch() format in C++. In which I keep getting errors. Here is some of my code too assist you in seeing my dilemma.
c:usersmrrosedocumentsvisual studio 2008projectshardmotelhardmotelhardmotel.cpp(125) : warning C4996: ‘getch’: The POSIX name for this item is deprecated. Instead, use the ISO C++ conformant name: _getch. See online help for details.
Here is the sample coding I have:
cout<<
«nntttWrong choice…..!!!»;
cout<<
«ntttPress any key to continue….!!»;
getch();
Any Suggestions are welcome.. Thanks to all..!!
-
Moved by
Monday, December 15, 2014 2:38 AM
C++ Related
-
Moved by
Answers
-
If I were you I would read the error, specifically the «warning C4996: ‘getch’: The POSIX name for this item is deprecated. Instead, use the ISO C++ conformant name: _getch. See online help for details.» and then I’d change the function
name of getch to the ISO C++ conformant name _getch(); making your code:cout<<"nntttWrong choice.....!!!"; cout<<"ntttPress any key to continue....!!"; _getch();
Hope this helps!
Sincerely, Jakeinc
-
Proposed as answer by
void123456789
Monday, December 15, 2014 3:38 AM -
Marked as answer by
Shu 2017
Monday, December 22, 2014 11:32 AM
-
Proposed as answer by
-
You simply can do it by using do .. while{} loop .Enter you choice read it poerform the req operation based on input and once you are done you can ask for what else he want to do etc. Second instead of getch() you simply can use std::cin.get();
Thanks
Rupesh Shukla
-
Edited by
Pintu Shukla
Monday, December 15, 2014 9:52 PM -
Marked as answer by
Shu 2017
Monday, December 22, 2014 11:32 AM
-
Edited by
-
If you intended this block of code to present the error message to the use and then allow him time to read and think about it before continuing, you will run into another problem. The cin or other input method into which the user entered
the wrong value will often leave residual data in the input buffer. (If the input was well formed, this residual data is just the ‘n’ character that resulted from the Enter key being pressed.) Calling getch or _getch will grab that residual
character immediately and your program will continue to the next statement without waiting at all.By the way, the diagnostic message you quoted is labeled a warning, not an error. The fact that Microsoft deprecates a function does not mean the function will not work as intended. You can ignore the warning or use #pragma to suppress
it if you so choose.-
Marked as answer by
Shu 2017
Monday, December 22, 2014 11:32 AM
-
Marked as answer by
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?
asked May 2, 2009 at 14:53
Duncan BenoitDuncan Benoit
3,2278 gold badges28 silver badges26 bronze badges
5
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.
answered May 2, 2009 at 14:57
1
If you’re into C++, why printf
and getch
? Consider using cout
and cin.get
instead.
answered May 2, 2009 at 15:04
Eli BenderskyEli Bendersky
258k88 gold badges347 silver badges410 bronze badges
1
use _getch() instead of getch()
answered Apr 2, 2013 at 19:07
1
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()
.
answered May 2, 2009 at 15:05
Brian CampbellBrian Campbell
317k56 gold badges358 silver badges339 bronze badges
2
Why do you need this? Why not use getchar()
if you need to capture a single character?
answered May 2, 2009 at 14:56
dirkgentlydirkgently
107k16 gold badges129 silver badges187 bronze badges
2
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.
answered Feb 2, 2019 at 11:19
aariowaariow
761 silver badge9 bronze badges
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?
asked May 2, 2009 at 14:53
Duncan BenoitDuncan Benoit
3,2278 gold badges28 silver badges26 bronze badges
5
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.
answered May 2, 2009 at 14:57
1
If you’re into C++, why printf
and getch
? Consider using cout
and cin.get
instead.
answered May 2, 2009 at 15:04
Eli BenderskyEli Bendersky
258k88 gold badges347 silver badges410 bronze badges
1
use _getch() instead of getch()
answered Apr 2, 2013 at 19:07
1
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()
.
answered May 2, 2009 at 15:05
Brian CampbellBrian Campbell
317k56 gold badges358 silver badges339 bronze badges
2
Why do you need this? Why not use getchar()
if you need to capture a single character?
answered May 2, 2009 at 14:56
dirkgentlydirkgently
107k16 gold badges129 silver badges187 bronze badges
2
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.
answered Feb 2, 2019 at 11:19
aariowaariow
761 silver badge9 bronze badges
Once upon a time, if you called a function which the compiler had never heard of, like this:
#include <stdio.h>
int main()
{
int x = foo();
printf("%dn", foo);
}
Anyway, if you did that, the compiler quietly assumed that foo()
was a function returning int
. That is, the compiler behaved just as if you had typed
extern int foo();
somewhere before you called foo
.
But in, I think, C99, the language was changed. It was no longer legal to call a function you had not explicitly declared. Because there was lots and lots of code out there that was written under the previous set of rules, most compilers did not immediately begin rejecting the old-style code. Some continued to quietly assume that unrecognized functions returned int
. Others — like yours — began noisily assuming that unrecognized functions returned int
, emitting warnings along the lines of «‘foo’ undefined, assuming extern returning int».
It sounds like your question is that some time ago, your code containing calls to getch()
was accepted without warning, but today, you’re getting the warning «‘getch’ undefined, assuming extern returning int». What changed?
One possibility is that your code changed slightly. If your code used to contain the line
#include <conio.h>
somewhere, that file would have contained a declaration along the lines of
extern int getch();
and this would have goven the compiler the declaration that it needed, and you would not have gotten the warning. But if today your code does not contain that #include
line, that explain why the warning started cropping up.
It’s also possible that your compiler has changed somehow. It’s possible you’re using a new version of the compiler, that’s more fussy, that has gone from quietly assuming, to normally assuming. Or, it’s possible that your compiler options have changed. Many compilers can be configured to accept different variants of the language, corresponding to the different versions of the language standards that have been released over the years. For example, if some time ago your compiler was compiling for language standard «C89», but today, it’s doing «C99» or «C11», that would explain why it’s now being noisy with this warning.
The change in the compiler could be a change in the defaults as configured by a system administrator, or a change in the way you’re invoking the compiler, or a change in your project’s Makefile, or a change in the language settings in your IDE, or something like that.
A few more points:
getch
is not a Standard C function; it’s specific to Windows. Your program would be more portable, in general, if you didn’t use it. Are you sure you need it? (I know what it’s for; what I don’t know if there’s some other way of keeping your program’s output window on the screen after if exits.)- You should get in the habit of declaring
main()
asint
, notvoid
. (void
will work well enough, but it’s not correct, and if nothing else, you’ll get lots of negative comments about it.) - I think there’s something wrong with your call to
strcpy_S
, too,
Once upon a time, if you called a function which the compiler had never heard of, like this:
#include <stdio.h>
int main()
{
int x = foo();
printf("%dn", foo);
}
Anyway, if you did that, the compiler quietly assumed that foo()
was a function returning int
. That is, the compiler behaved just as if you had typed
extern int foo();
somewhere before you called foo
.
But in, I think, C99, the language was changed. It was no longer legal to call a function you had not explicitly declared. Because there was lots and lots of code out there that was written under the previous set of rules, most compilers did not immediately begin rejecting the old-style code. Some continued to quietly assume that unrecognized functions returned int
. Others — like yours — began noisily assuming that unrecognized functions returned int
, emitting warnings along the lines of «‘foo’ undefined, assuming extern returning int».
It sounds like your question is that some time ago, your code containing calls to getch()
was accepted without warning, but today, you’re getting the warning «‘getch’ undefined, assuming extern returning int». What changed?
One possibility is that your code changed slightly. If your code used to contain the line
#include <conio.h>
somewhere, that file would have contained a declaration along the lines of
extern int getch();
and this would have goven the compiler the declaration that it needed, and you would not have gotten the warning. But if today your code does not contain that #include
line, that explain why the warning started cropping up.
It’s also possible that your compiler has changed somehow. It’s possible you’re using a new version of the compiler, that’s more fussy, that has gone from quietly assuming, to normally assuming. Or, it’s possible that your compiler options have changed. Many compilers can be configured to accept different variants of the language, corresponding to the different versions of the language standards that have been released over the years. For example, if some time ago your compiler was compiling for language standard «C89», but today, it’s doing «C99» or «C11», that would explain why it’s now being noisy with this warning.
The change in the compiler could be a change in the defaults as configured by a system administrator, or a change in the way you’re invoking the compiler, or a change in your project’s Makefile, or a change in the language settings in your IDE, or something like that.
A few more points:
getch
is not a Standard C function; it’s specific to Windows. Your program would be more portable, in general, if you didn’t use it. Are you sure you need it? (I know what it’s for; what I don’t know if there’s some other way of keeping your program’s output window on the screen after if exits.)- You should get in the habit of declaring
main()
asint
, notvoid
. (void
will work well enough, but it’s not correct, and if nothing else, you’ll get lots of negative comments about it.) - I think there’s something wrong with your call to
strcpy_S
, too,