Ошибка c4996 c getch

mster-doc

16 / 16 / 12

Регистрация: 10.11.2012

Сообщений: 245

1

23.02.2016, 10:52. Показов 41248. Ответов 10

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Здравствуйте.

Не понимаю в чём ошибка.
Вроде как не первый раз использую этот код, но в первые сталкиваю с этой проблемой.

Кликните здесь для просмотра всего текста

C++
1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <conio.h>
 
using namespace std;
 
int name()
{
    getch();
    return 0;
}

Сообщение об ошибке:
Severity Code Description Project File Line Suppression State
Error C4996 ‘getch’: The POSIX name for this item is deprecated. Instead, use the ISO C and C++ conformant name: _getch. See online help for details. ConsoleApplication1 c:usersmster-docdesktopc++ practiceconsoleapplication1consoleapplication1main.cpp 8



0



3434 / 2813 / 1249

Регистрация: 29.01.2016

Сообщений: 9,426

23.02.2016, 11:04

2

Лучший ответ Сообщение было отмечено Kerry_Jr как решение

Решение

Студия выдаёт?

Добавлено через 6 минут
Особенности студий после 10-й. Меняй на _getch.
Security Development Lifecyde (SDL)
Как отключить в свойствах проекта:
https://www.cyberforum.ru/post5488517.html

Или, выше всех инклудов, прописать: #define _CRT_SECURE_NO_WARNINGS (для getch() не работает, нужно заменить на _getch()).

Или, ниже всех инклудов, прописать: #pragma warning(disable : 4996)



3



Эксперт PHP

3105 / 2590 / 1219

Регистрация: 14.05.2014

Сообщений: 7,236

Записей в блоге: 1

23.02.2016, 11:06

3

Лучший ответ Сообщение было отмечено Kerry_Jr как решение

Решение

Цитата
Сообщение от mster-doc
Посмотреть сообщение

‘getch’: The POSIX name for this item is deprecated. Instead, use the ISO C and C++ conformant name: _getch.

Тут четко написано: Имя в POSIX-стиле для этой функции устарело. Вместо него используй _getch.



2



16 / 16 / 12

Регистрация: 10.11.2012

Сообщений: 245

23.02.2016, 11:25

 [ТС]

4

Хмм… (( Я перепробовал все вышеперечисленные варианты. Не получилось…
отключал при старом коде Security Development Lifecyde (SDL) , не помогло
Потом возвращял Security Development Lifecyde (SDL) как было на yes и
заменял на _getch(); и прописывал выше всех инклудов, прописать: #define _CRT_SECURE_NO_WARNINGS
заменял на _getch(); и прописывал ниже всех инклудов, прописать: #pragma warning(disable : 4996);
даже просто заменял на _getch(); не вышло…



0



3434 / 2813 / 1249

Регистрация: 29.01.2016

Сообщений: 9,426

23.02.2016, 11:28

5

Цитата
Сообщение от mster-doc
Посмотреть сообщение

даже просто заменял на _getch(); не вышло…

Все другие способы, именно для getch(), не действуют:

Цитата
Сообщение от nd2
Посмотреть сообщение

(для getch() не работает, нужно заменить на _getch()).

Замена на _getch() должна работать. Студия какая?



0



3434 / 2813 / 1249

Регистрация: 29.01.2016

Сообщений: 9,426

23.02.2016, 11:31

6

Миниатюры

Ошибка в getch: Error C4996
 



1



3434 / 2813 / 1249

Регистрация: 29.01.2016

Сообщений: 9,426

23.02.2016, 11:33

7

Цитата
Сообщение от mster-doc
Посмотреть сообщение

int name()
{

Это у тебя точка входа такая?



1



16 / 16 / 12

Регистрация: 10.11.2012

Сообщений: 245

23.02.2016, 11:39

 [ТС]

8

Я ранее буквально на прошлой неделе в этой же Visual Stodio 2015 использовал
#include <conio.h>
getch();

и там компилится без проблем. Я даже свойства проекта изменил как у того и всё ровно не работает.



0



3434 / 2813 / 1249

Регистрация: 29.01.2016

Сообщений: 9,426

23.02.2016, 11:44

9

Цитата
Сообщение от mster-doc
Посмотреть сообщение

Я ранее буквально на прошлой неделе в этой же Visual Stodio 2015 использовал
#include <conio.h>
getch();
и там компилится без проблем. Я даже свойства проекта изменил как у того и всё ровно не работает.

Как там было на прошлой неделе — это один ты знаешь. На скринах (6 пост и здесь) — работа кода в 15 -й студии (Community).

Миниатюры

Ошибка в getch: Error C4996
 



1



mster-doc

16 / 16 / 12

Регистрация: 10.11.2012

Сообщений: 245

23.02.2016, 11:44

 [ТС]

10

Да. Всем спасибо.
Создал консольное приложение по другому и теперь

Кликните здесь для просмотра всего текста

C++
1
2
3
4
5
6
7
8
9
10
#include<iostream>
#include<conio.h>
 
using namespace std;
 
int main()
{
    _getch();
    return 0;
}

Работает. Всем спасибо.



0



0 / 0 / 0

Регистрация: 21.06.2019

Сообщений: 1

21.06.2019, 12:31

11

Visual Studio 2017: вместо getche() идентично работает _gettche();
а вместо getch() работает _gettch().
Проблема _getch() что функция вызывается дважды.



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

21.06.2019, 12:31

11

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?

Jonathan Leffler's user avatar

asked May 2, 2009 at 14:53

Duncan Benoit's user avatar

Duncan BenoitDuncan Benoit

3,2878 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.

Community's user avatar

answered May 2, 2009 at 14:57

Johannes Schaub - litb's user avatar

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 Bendersky's user avatar

Eli BenderskyEli Bendersky

262k88 gold badges350 silver badges412 bronze badges

1

use _getch() instead of getch()

answered Apr 2, 2013 at 19:07

shahzaib's user avatar

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 Campbell's user avatar

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

dirkgently's user avatar

dirkgentlydirkgently

108k16 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

aariow's user avatar

aariowaariow

741 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 !

  • Remove From My Forums
  • Question

  • Hi

    I Mack a New Test Project in Visual Studio 2012 on C++ language.
    I  following this:
    Chose C++> empty Project> Right Click In Solution> add New Item>  C++ File (*.cpp)
    So is Good but I type the following code:

    #include <iostream>
    #include <conio.h>
    #include <stdio.h>
    #include <wchar.h>
    
    using namespace std;
    
    int main()
    {
     cout<<"welcom";
     return 0;
     getch();
    }

    When I Run My Program and this is the error message after The compile it:
    Error 1 error C4996: ‘getch’: The POSIX name for this item is deprecated. Instead, use the ISO C++ conformant name: _getch. See online help for details. c:usersDavid Ceracdocumentsvisual studio 2012projectstest 2test 2source.cpp 12 1 test 2
    I change getch (); TO _getch (); so Compiler Remove Error But When I See result My Code On the screen My App Don’ Pause. I’m Confused That it. How Can I Stop my App & Pause this on the Screen?????

    • Edited by

      Monday, November 11, 2013 7:31 AM

Answers

  • » I See result My Code On the screen My App Don’ Pause. I’m Confused That it. How Can I Stop my App & Pause this on the Screen?????»

    You’ve placed the _getch after return, _getch will never be executed and of course that your app won’t pause.

    Also note that you could use getchar, which is a standard C library function, instead of getch/_getch.

    • Marked as answer by
      David Cerac
      Monday, November 11, 2013 7:34 AM
    • Unmarked as answer by
      David Cerac
      Monday, November 11, 2013 7:34 AM
    • Marked as answer by
      David Cerac
      Monday, November 11, 2013 7:34 AM

  • I Fine Solution……..

    Is solve for Example:

    #include <iostream>
    #include <conio.h>
    #include <stdio.h>
    
    using namespace std;
    
    int main()
    {
    	cout<<"welcom";
    	_getch ();
    	return 0;
    }
    
    • Marked as answer by
      David Cerac
      Monday, November 11, 2013 7:35 AM

Solution 1

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.

Solution 2

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

Solution 3

use _getch() instead of getch()

Solution 4

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().

Solution 5

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

Related videos on Youtube

error C4996: "This function or variable may be unsafe" in MS Visual Studio 2013 for Windows Desktop

01 : 43

error C4996: «This function or variable may be unsafe» in MS Visual Studio 2013 for Windows Desktop

Difference between getch() , getche() and getchar()

08 : 12

Difference between getch() , getche() and getchar()

Mahajan — The Best Programming Tutorials

Difference between gets(),getch(),getche(),getchar()-c program tutorial

03 : 20

Difference between gets(),getch(),getche(),getchar()-c program tutorial

getc, getch, getche and getchar in C

06 : 33

getc, getch, getche and getchar in C

Using APT keys | GPG and Third Party Keys Explained

10 : 42

Using APT keys | GPG and Third Party Keys Explained

So sánh fgets() vs gets()

07 : 30

So sánh fgets() vs gets()

Hướng dẫn sửa lỗi C4996 trong Visual Studio

04 : 20

Hướng dẫn sửa lỗi C4996 trong Visual Studio

Vulnerabilities of the gets function in C

08 : 35

Vulnerabilities of the gets function in C

getAdapterPosition() is deprecated - Android

01 : 28

getAdapterPosition() is deprecated — Android

getColorStateList has been deprecated - Android

01 : 01

getColorStateList has been deprecated — Android

Comments

  • 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?

    • Did you read the error message?

    • @jalf: The «error message» is wrong/misleading, so I don’t see how reading it would help…

    • @R..: No it isn’t. It very clearly states the compiler’s reason for issuing the warning, and it states just as clearly what they want you to do to avoid the warning. You and I may not agree with Microsoft’s unilateral decision to «deprecate» standard functions, but the warning very clearly explains the issue, whether or not you agree with the underlying reasoning. If you want the warning to go away, and the warning actually says «please use this function instead», then reading the warning certainly helps.

    • Mentioning POSIX is what’s wrong and misleading; this has nothing to do with POSIX. Moreover the function is not a standard function; it’s a function name used by conio (and I believe also curses) for interactive single-character reads from the keyboard with no buffering.

  • getchar is line buffered, thus it will wait for a newline character. _getch() won’t, but return immediately. I can understand him sometimes it’s really useful («press x to zoom», for example).

  • I don’t think it has anything to do with buffering. getchar() reads in a character at a time. There is then fgets and the entire range of Xscanf() functions (albeit difficult to use). But as I said, it is difficult to suggest something without proper context, particularly a non-standard extension.

  • getch has little to do with getchar. Rather it’s a conio (and I believe also curses) interface whose purpose is to interactively read a single character from the keyboard without buffering/delay.

  • Could you explain why the asker should use one instead of the other? Fixing the problem is good but understanding the problem and why the solution works is even better.

  • I’m not sure cin / cing.get works eg with arrow keys

  • POSIX doesn’t come into it in the case of this particular function, but most of the functions that were deprecated in favour of underscore versions were POSIX-like functions such as open or mkdir. Guess they just didn’t want to bother creating a separate warning message for the few exceptions.

  • Actually there is a difference between getchar and getch. getch blocks until some key is pressed. getchar blocks until enter is pressed.

Recents

Related

  • Ошибка c4703 используется потенциально неинициализированная локальная переменная указатель
  • Ошибка c4700 использована неинициализированная локальная переменная
  • Ошибка c4600 kyocera 6530
  • Ошибка c46 gsxr 750
  • Ошибка c426 пежо боксер