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,2778 gold badges29 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
261k88 gold badges350 silver badges412 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
321k57 gold badges360 silver badges340 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 badges131 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
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 !
mster-doc 16 / 16 / 12 Регистрация: 10.11.2012 Сообщений: 245 |
||||
1 |
||||
23.02.2016, 10:52. Показов 41035. Ответов 10 Метки нет (Все метки)
Здравствуйте. Не понимаю в чём ошибка. Кликните здесь для просмотра всего текста
Сообщение об ошибке:
0 |
3434 / 2813 / 1249 Регистрация: 29.01.2016 Сообщений: 9,426 |
|
23.02.2016, 11:04 |
2 |
РешениеСтудия выдаёт? Добавлено через 6 минут Или, выше всех инклудов, прописать: #define _CRT_SECURE_NO_WARNINGS (для getch() не работает, нужно заменить на _getch()). Или, ниже всех инклудов, прописать: #pragma warning(disable : 4996)
3 |
3105 / 2590 / 1219 Регистрация: 14.05.2014 Сообщений: 7,236 Записей в блоге: 1 |
|
23.02.2016, 11:06 |
3 |
Решение
‘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 |
3434 / 2813 / 1249 Регистрация: 29.01.2016 Сообщений: 9,426 |
|
23.02.2016, 11:28 |
5 |
даже просто заменял на _getch(); не вышло… Все другие способы, именно для getch(), не действуют:
(для getch() не работает, нужно заменить на _getch()). Замена на _getch() должна работать. Студия какая?
0 |
3434 / 2813 / 1249 Регистрация: 29.01.2016 Сообщений: 9,426 |
|
23.02.2016, 11:31 |
6 |
… Миниатюры
1 |
3434 / 2813 / 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 |
3434 / 2813 / 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 |
Здравствуйте уважаемые пользователи!
Компилирую программу на C++
Не получается скомпилировать даже простейшею программу!
Компилятор: MiniGW
IDE: NetBeans
Лог компилятора
"/C/MinGW/msys/1.0/bin/make.exe" -f nbproject/Makefile-Release.mk QMAKE= SUBPROJECTS= .build-conf
make.exe[1]: Entering directory `/c/ShevchProgramms/learn/HelloWorld'
"/C/MinGW/msys/1.0/bin/make.exe" -f nbproject/Makefile-Release.mk dist/Release/MinGW-Windows/helloworld.exe
make.exe[2]: Entering directory `/c/ShevchProgramms/learn/HelloWorld'
mkdir -p build/Release/MinGW-Windows
rm -f "build/Release/MinGW-Windows/newfile.o.d"
g++ -c -O2 -MMD -MP -MF "build/Release/MinGW-Windows/newfile.o.d" -o build/Release/MinGW-Windows/newfile.o newfile.cpp
newfile.cpp:2:19: conio.h: No such file or directory
newfile.cpp: In function `int main()':
newfile.cpp:8: error: `getch' undeclared (first use this function)
newfile.cpp:8: error: (Each undeclared identifier is reported only once for each function it appears in.)
newfile.cpp: At global scope:
newfile.cpp:12: error: expected constructor, destructor, or type conversion before '(' token
newfile.cpp:12: error: expected `,' or `;' before '(' token
make.exe[2]: *** [build/Release/MinGW-Windows/newfile.o] Error 1
make.exe[2]: Leaving directory `/c/ShevchProgramms/learn/HelloWorld'
make.exe[1]: *** [.build-conf] Error 2
make.exe[1]: Leaving directory `/c/ShevchProgramms/learn/HelloWorld'
make.exe": *** [.build-impl] Error 2
СОБРАТЬ FAILED (значение выхода 2,, общее время: 3s)
Исходный код программы:
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
cout<<"Hello World!";
getch();
return 0;
}
Если убрать getch то всё работает!
Та же самая ошибка при использовании system и остальных кодов.
Почему он не хочет их компилировать?
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,