|
mster-doc 16 / 16 / 12 Регистрация: 10.11.2012 Сообщений: 245 |
||||
|
1 |
||||
|
23.02.2016, 10:52. Показов 35919. Ответов 10 Метки нет (Все метки)
Здравствуйте. Не понимаю в чём ошибка. Кликните здесь для просмотра всего текста
Сообщение об ошибке:
__________________
0 |
|
3433 / 2812 / 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 |
|
3101 / 2586 / 1219 Регистрация: 14.05.2014 Сообщений: 7,231 Записей в блоге: 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 |
|
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 |
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
257k88 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
316k56 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
106k16 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
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
Class Will Not Run
For an assignment, I’m supposed to create a class called piano and then use the methods:
1-) LoadNotes. This function takes a string as a parameter, the parameter is a file name that contains notes. The notes are already shown in the code you’re given. Load Notes should read the notes into an array of characters (or strings)
2-) PlayNotes. This function simply plays the notes that were loaded by LoadNotes.
However, whenever I try to run the code in visual studio it stops working at line 18. Are there any hints you could give me or any easy fixes to make my code run? Any help would be greatly appreciated.
|
|
Last edited on
please use code tags for code. soon people will stop answering if you do not.
a class creates a new type.
where is main()?
you should have a main:
|
|
Which line is 18? If you would use code tags in the post, then it would be easy to see. Read https://www.cplusplus.com/articles/jEywvCM9/
Your code in tags and with some indentation:
|
|
Is the line 18 this: void LoadNotes(string mynotes.txt)?
What exactly does the visual studio give as error message?
Note:
The general rules for naming variables are:
* Names can contain letters, digits and underscores
* Names must begin with a letter or an underscore (_)
* Names are case sensitive (myVar and myvar are different variables)
* Names cannot contain whitespaces or special characters like !, #, %, etc.
* Reserved words (like C++ keywords, such as int) cannot be used as names
Your name for a variable, the mynotes.txt, violates one of them. Dot is not a letter, digit, nor underscore.
See http://www.cplusplus.com/doc/tutorial/files/ too.
Last edited on
Variable names cannot have ‘.’s in them. String literals should have «» around them.
|
|
The return statement at the end of a void function is not necessary.
Last edited on
note that your ifstream is a local and is opened, then destroyed.
you need to read it into a container or something.
I took into account what y’all had to say and made some changes, but I still can’t get it to run. Whenever I try, I get the following error messages:
Error (active) E0065 expected a ‘;’ ConsoleApplication2 16
Error (active) E0415 no suitable constructor exists to convert from «const char [1]» to «Piano» ConsoleApplication2 17
Error (active) E0169 expected a declaration ConsoleApplication2 18
Error (active) E0070 incomplete type is not allowed ConsoleApplication2 23
Error (active) E0020 identifier «filename» is undefined ConsoleApplication2 23
Error (active) E0135 class «Piano» has no member «LoadNotes» ConsoleApplication2 28
Error C2143 syntax error: missing ‘;’ before ‘}’ ConsoleApplication2 16
Error C2440 ‘initializing’: cannot convert from ‘const char [1]’ to ‘Piano’ ConsoleApplication2 17
Error C2447 ‘{‘: missing function header (old-style formal list?) ConsoleApplication2 18
Error C2079 ‘input_file’ uses undefined class ConsoleApplication2 23
Error C2065 ‘filename’: undeclared identifier ConsoleApplication2 23
Error C2039 ‘LoadNotes’: is not a member of ‘Piano’ ConsoleApplication2 28
Error C2731 ‘main’: function cannot be overloaded ConsoleApplication2 32
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. ConsoleApplication2 36
|
|
Last edited on
Remove <conio.h> and <windows.h>, you do not need them.
Add #include <string>
Add #include <fstream>
Something got severely messed up with your declaration of LoadNotes.
Let’s just start with a simple, minimal example:
|
|
Last edited on
|
|
The rest of errors are just due to the compiler having already fallen off the track.
Except …
Error C2731 'main': function cannot be overloaded ConsoleApplication2 32 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. ConsoleApplication2 36
You show only 29 lines of code and these errors come from lines 32 and 36?
Do you now have int main() twice? Why don’t you show the one that you have, rather than blindly copy-pasting the second implementation of main()?
keskiverto
My code up to this point is:
|
|
My professor gave us code to test it with (the code is down below:)
|
|
Last edited on
The reason I had originally said to not use #include <conio.h> #include <windows.h> were that they were non-standard headers, and you weren’t using their functionality in the code you posted. Your latest post supersedes this.
First, you should ask your professor exactly what compiler he or she is using. Ideally, you should compile with whatever compiler/toolchain your professor will use to grade you with. Because getch() is non-standard, different compilers range in strictness regarding it.
Error C4996 ‘getch’: The POSIX name for this item is deprecated. Instead, use the ISO C and C++ conformant name: _getch
Your compiler wants you to use _getch() instead of getch(). Ask your professor if this is OK.
______________________
If you combine your Piano class with your professor’s driver code, these are the headers you need:
|
|
Last edited on
My professor is using windows visual studio, although I am not sure what version. Other than the getch error, are you saying that my could should run?
Last edited on
Other than the getch error, are you saying that my could should run?
Yes. Assuming you fix syntax issues in your second post, don’t have two different mains, have proper includes, etc.
I was able to fix my code and wanted to thank everyone who helped.
Here is the running code:
|
|
As PlayNotes() is really the professor’s test code, then I’m not enthused with his code. There’s much better ways of doing this than a long list of if statements…
… furthermore, that code does not «test» class Piano. It is closer to sample implementation of the «PlayNotes».
Surely a proper «test driver» can be used as is, without any modification?
Topic archived. No new replies allowed.
Для новичков в C ++ использование современных инструментов может стать большой головной болью, особенно когда версия VS вашей школы довольно старая и у вас дома установлена последняя версия VS. Одним из самых известных упражнений для студентов, является знаменитый привет мир на этом языке. Играя с консольным приложением, упражнение простое, напечатайте «привет мир» и держите консоль открытой, чтобы увидеть напечатанное сообщение. В соответствии со стилем программирования вашего учителя вы можете получить пример кода с помощью cout:
#include
#include
using namespace std;
void main(void)
{
cout << "Hello World" << endl;
getch();
}
Или используя printf чтобы распечатать текст в консоли:
#include
#include
void main(void)
{
printf("Hello World");
getch();
}
Оба сценария полностью допустимы и используют метод getch, чтобы держать консоль открытой. Они должны нормально работать в компиляторах школы, где VS всегда устарел, однако, если вы используете современный компилятор для компиляции любого из предыдущих примеров (используя последнюю версию Visual Studio), вы столкнетесь с исключением. Проблема в том, что метод getch является нестандартной функцией, и компиляторы MS традиционно предлагали их под двумя именами, но Microsoft решила определить имя без подчеркивания как устаревшее, потому что эти имена зарезервированы для программиста.
Решение
Самый простой способ решения этой проблемы — использовать _getch метод с подчеркиванием в качестве префикса:
#include
#include
using namespace std;
void main(void)
{
cout << "Hello World" << endl;
// Use the getch method with a prefixed underscore
_getch();
}
Этот метод работает так же, но не будет признан устаревшим. Вы также можете использовать cin.get метод пространства имен std:
#include
#include
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();
}
See more:
Hi, I’ve created new project in visual studio 2019 and import code resource from the original file. But when compiled it came with this error:
C4996: ‘getch’:the POSIX name for this item is deprecated. Instead, use the ISO C and C++ conformant name: _getch
Here is the program at the place the error was showed:
int c; dltXY = XY_DLT; dltAB = AB_DLT; flag_move = 0; c = getch(); c = toupper(c); if (c == 'Q') return 1;
What I have tried:
I’ve tried to fix the other problem that is about
struct sockaddr_in sa
function but I don’t understand this error so I’m stuck with it.
Do what the error message tells you and change the function call to _getch(). Converting VC++ 6.0 code may find a number of incompatible functions; you just have to change them to conform to the latest standards.
See Compiler Warning (level 3) C4996 | Microsoft Docs[^] for an explanation. Note that it is not recommended to disable this warning message.
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
CodeProject,
20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8
+1 (416) 849-8900
See more:
Hi, I’ve created new project in visual studio 2019 and import code resource from the original file. But when compiled it came with this error:
C4996: ‘getch’:the POSIX name for this item is deprecated. Instead, use the ISO C and C++ conformant name: _getch
Here is the program at the place the error was showed:
int c; dltXY = XY_DLT; dltAB = AB_DLT; flag_move = 0; c = getch(); c = toupper(c); if (c == 'Q') return 1;
What I have tried:
I’ve tried to fix the other problem that is about
struct sockaddr_in sa
function but I don’t understand this error so I’m stuck with it.
Do what the error message tells you and change the function call to _getch(). Converting VC++ 6.0 code may find a number of incompatible functions; you just have to change them to conform to the latest standards.
See Compiler Warning (level 3) C4996 | Microsoft Docs[^] for an explanation. Note that it is not recommended to disable this warning message.
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
CodeProject,
20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8
+1 (416) 849-8900
Сообщение было отмечено Kerry_Jr как решение
