Error c4996 getch

Ошибка в getch: Error C4996 C++ Решение и ответ на вопрос 1668857

mster-doc

16 / 16 / 12

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

Сообщений: 245

1

23.02.2016, 10:52. Показов 36096. Ответов 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++ practiceconsoleapplication1consoleapplication1m ain.cpp 8

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



3433 / 2812 / 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

3102 / 2587 / 1219

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

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

Записей в блоге: 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



3433 / 2812 / 1249

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

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

23.02.2016, 11:28

5

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

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

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

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

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

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



0



3433 / 2812 / 1249

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

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

23.02.2016, 11:31

6

Миниатюры

Ошибка в getch: Error C4996
 



1



3433 / 2812 / 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



3433 / 2812 / 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

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 !

Содержание

  1. How to solve C++ Error C4996 ‘getch’: The POSIX name for this item is deprecated. Instead, use the ISO C and C++ conformant name: _getch
  2. Solution
  3. C error c4996 getch
  4. Answered by:
  5. Question
  6. Answers
  7. Thread: warning C4996: ‘getch’: The POSIX name for this item is deprecated.
  8. warning C4996: ‘getch’: The POSIX name for this item is deprecated.
  9. C error c4996 getch
  10. C error c4996 getch

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

Carlos Delgado

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:

Or using printf to print the text in the console:

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:

Источник

C error c4996 getch

This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.

Answered by:

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:

«ntttPress any key to continue. » ;

Any Suggestions are welcome.. Thanks to all.

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:

Hope this helps!

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

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.

Источник

Thread: warning C4996: ‘getch’: The POSIX name for this item is deprecated.

Thread Tools
Search Thread
Display

warning C4996: ‘getch’: The POSIX name for this item is deprecated.

Hello
I have no idea what does this error message means.
the error message is related to the switch statement in function paintGame.
It is not the complete code I just put the codes that might help to understand it.

any suggestion would be appreciated.
Thanks

I can’t see how it’s realted to the switch statement. You don’t call getch() there.

The problem is that getch() is a non-standard function, and MS compilers have traditionally offered those under two names — once simply as they are, once with a leading underscore (_getch()), as befits a standard library extension. Apparently, the new compilers warn that the versions without the leading underscore (misleadingly called «POSIX names» — that’s because the same warning also applies to the POSIX compatibility functions the compiler offers) are deprecated, i.e. they might go away in a future version of the compiler.

The solution is to use _getch() instead of getch(), or better yet, use something else entirely.

All the buzzt!
CornedBee

«There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code.»
— Flon’s Law

Источник

C error c4996 getch

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.

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.

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.

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

Источник

C error c4996 getch

Can you help me remove these errors? I try to start to build program, one of my first tries, to capture content of window. I took this script which originally should capture screen and try to remake it.

update
cpp: pls see the actual code and reports bellow

I had forgotten there must me main function. I removed the code for this one, looks better:

EDIT
It still generates errors:

—— Rebuild All started: Project: capture2, Configuration: Debug Win32 ——
stdafx.cpp
capture.cpp
s:tempc++algoritmycapture2capturecapture.cpp(13): warning C4996: ‘getch’: The POSIX name for this item is deprecated. Instead, use the ISO C++ conformant name: _getch. See online help for details.
p:programyprogramováníc++visual studio 10.0vcincludeconio.h(128) : see declaration of ‘getch’
s:tempc++algoritmycapture2capturecapture.cpp(28): error C2440: ‘initializing’ : cannot convert from ‘HGDIOBJ’ to ‘HBITMAP’
Conversion from ‘void*’ to pointer to non-‘void’ requires an explicit cast
s:tempc++algoritmycapture2capturecapture.cpp(30): error C2065: ‘width’ : undeclared identifier
s:tempc++algoritmycapture2capturecapture.cpp(30): error C2065: ‘height’ : undeclared identifier
s:tempc++algoritmycapture2capturecapture.cpp(31): error C2440: ‘=’ : cannot convert from ‘HGDIOBJ’ to ‘HBITMAP’
Conversion from ‘void*’ to pointer to non-‘void’ requires an explicit cast
Generating Code.
========== Rebuild All: 0 succeeded, 1 failed, 0 skipped ==========

I have finally found good script which after correction works. I remake it now to capture from window, but here I have a question. I try to use GdipCreateBitmapFromHBITMAP()

but result is error:

error C3861: ‘GdipCreateBitmapFromHBITMAP’: identifier not found
I even try to include
But still the same. How to fix?

Can you help to solve unresolved external problem in program using GDI+ Flat API?

Источник

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

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

258k88 gold badges347 silver badges410 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

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

dirkgently's user avatar

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

aariow's user avatar

aariowaariow

761 silver badge9 bronze badges

  • 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

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

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <cstdlib>
#include <iostream>
#include <conio.h>
#include <windows.h>
using namespace std;

class Piano 
{
//Member variables
private:
string notes;
//Member functions
 public:
//default constructor
Piano() {
notes = "";
}
void LoadNotes(string mynotes.txt)
{
char note;
ifstream input_file(mynotes.txt);
return;

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:

1
2
3
4
5
6
7
int main()
{
  //and it should contain your variable:
   Piano p;
   //and you can use that:
   p.LoadNotes("file");
}

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <cstdlib>
#include <iostream>
#include <conio.h>
#include <windows.h>
using namespace std;

class Piano {
    //Member variables
private:
    string notes;
    //Member functions
public:
    //default constructor
    Piano() {
        notes = "";
    }
    //Load notes from file
    void LoadNotes(string mynotes.txt)
    {
        char note;
        ifstream input_file(mynotes.txt);
        return;
    }

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
void LoadNotes(string filename)
{
    ifstream input_file(filename);
    // ...
}

// ...

int main()
{
   Piano p; // borrowing from jonnin's post
   p.LoadNotes("mynotes.txt");
}

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <cstdlib>
#include <iostream>
#include <conio.h>
#include <windows.h>
using namespace std;

class Piano 
{
    //Member variables
private:
    string notes;
    //Member functions
public:
    //default constructor
    Piano();
}
        notes = "";
        {
            //Load notes from file
            void LoadNotes(string filename)
        }
        char note;
        ifstream input_file(filename);

int main()
{
    Piano p;
   p.LoadNotes("filenmae");
}

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// Example program
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

class Piano 
{
private:
    string notes;

public:
    void LoadNotes(string filename)
    {
        //Load notes from file
        ifstream input_file(filename);
        
        if (!input_file)
        {
            cout << "Error reading filen";
            return;
        }

        //
        // ... read from input_file here ...
        //
    }
};

int main()
{
    Piano p;
    p.LoadNotes("filename.txt");
}

Last edited on

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <cstdlib>
#include <iostream>
#include <conio.h>
#include <windows.h>
using namespace std;

class Piano 
{
    //Member variables
private:
    string notes;
    //Member functions
public:
    //default constructor
    Piano();
} // E0065 expected a ';'
// The definition of class must end with ;
// This closing brace matches the opening brace on line 8 

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Piano
{
private:
    string notes;

public:
    void LoadNotes(string filename)
    {
        //Load notes from file
        ifstream input_file(filename);

        if (!input_file)
        {
            cout << "Error reading filen";
            return;
        }

        //
        // ... read from input_file here ...
        //
    }
};

int main()
{
    Piano p;
    p.LoadNotes("filename");
}

My professor gave us code to test it with (the code is down below:)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include <cstdlib>
#include <iostream>
#include <conio.h>
#include <windows.h>
using namespace std;

int main(int argc, char *argv[])
{
  while(true){
              cout<<"Input note: ";
              char note = getch();
              
              
              //do re mi fa sol la si do re mi fa sol
              if(note == 'a'){
                      Beep(261,100);
                      }
              if(note == 's'){
                      Beep(293,100);
                      }
              if(note == 'd'){
                      Beep(329,100);
                      }
              if(note == 'f'){
                      Beep(349,100);
                      }
              if(note == 'g'){
                      Beep(392,100);
                      }
              if(note == 'h'){
                      Beep(440,100);
                      }
              if(note == 'j'){
                      Beep(493,100);
                      }                      
              if(note == 'k'){
                      Beep(523,100);
                      }                      
              if(note == 'l'){
                      Beep(587,100);
                      }
              if(note == ';'){
                      Beep(659,100);
                      }  
              if(note == '''){
                      Beep(698,100);
                      } 
               if(note == '\'){
                      Beep(784,100);
                      } 
                      
               //rebemol mibemol solbemol labemol sibemol rebemol mibemol solbemol
               if(note == 'w'){
                      Beep(277,100);
                      } 
                      if(note == 'e'){
                      Beep(311,100);
                      }
                      if(note == 't'){
                      Beep(370,100);
                      }
                      if(note == 'y'){
                      Beep(415,100);
                      }
                      if(note == 'u'){
                      Beep(466,100);
                      }
                      if(note == 'o'){
                      Beep(554,100);
                      }
                      if(note == 'p'){
                      Beep(622,100);
                      }
                      if(note == ']'){
                      Beep(740,100);
                      }     
                      
            system("cls");          
}  
    
    return EXIT_SUCCESS;
} 

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:

1
2
3
4
5
6
#include <cstdlib>   // EXIT_SUCCESS, system
#include <iostream>  // std::cout
#include <string>    // std::string
#include <fstream    // std::ifstream
#include <conio.h>   // getch or _getch
#include <windows.h> // Beep 

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#include <cstdlib>
#include <iostream>
#include <conio.h>
#include <windows.h>
#include<fstream>
using namespace std;
//Create a class Piano
class Piano {
	//Member variables
private:
	string notes;
	//Member functions
public:
	//default constructor
	Piano() {
		notes = "";
	}
	//Load notes from file
	void LoadNotes(string filename) {
		char note;
		ifstream input_file(filename);
		if (!input_file.is_open()) {
			cerr << "Could not open the file - '"
				<< filename << "'" << endl;
			return;
		}
		while (input_file.get(note)) {
			notes += note;
		}
		input_file.close();
	}
	//Play notes
	void PlayNotes() {
		for (const auto& note : notes) {
			if (note == 'a') {
				Beep(261, 100);
			}
			if (note == 's') {
				Beep(293, 100);
			}
			if (note == 'd') {
				Beep(329, 100);
			}
			if (note == 'f') {
				Beep(349, 100);
			}
			if (note == 'g') {
				Beep(392, 100);
			}
			if (note == 'h') {
				Beep(440, 100);
			}
			if (note == 'j') {
				Beep(493, 100);
			}
			if (note == 'k') {
				Beep(523, 100);
			}
			if (note == 'l') {
				Beep(587, 100);
			}
			if (note == ';') {
				Beep(659, 100);
			}
			if (note == ''') {
				Beep(698, 100);
			}
			if (note == '\') {
				Beep(784, 100);
			}
			//rebemol mibemol solbemol labemol sibemol rebemol mibemol solbemol
			if (note == 'w') {
				Beep(277, 100);
			}
			if (note == 'e') {
				Beep(311, 100);
			}
			if (note == 't') {
				Beep(370, 100);
			}
			if (note == 'y') {
				Beep(415, 100);
			}
			if (note == 'u') {
				Beep(466, 100);
			}
			if (note == 'o') {
				Beep(554, 100);
			}
			if (note == 'p') {
				Beep(622, 100);
			}
			if (note == ']') {
				Beep(740, 100);
			}
		}
	}
};
int main(int argc, char* argv[])
{
	//Create object
	Piano mypiano;
	//Load notes from file
	mypiano.LoadNotes("mynotes.txt");
	//Play
	mypiano.PlayNotes();
	return EXIT_SUCCESS;
}

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.

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


This compiler warning indicates that there is a reference to the ‘getch()’ function in the code. The compiler is suggesting that the code be updated to use the ‘_getch()’ function instead.

Generally, this error will occur in a Microsoft development environment. Way back, a long time ago, Microsoft introduced the ‘getch()’ [and ‘getche()’] functions. These functions would wait for the user to press a key, and then retun that key character back to the caller. The ‘getch()’ function would not ‘echo’ the key back to the (DOS or early Windows) screen, while ‘getche()’ would echo the key pressed to the screen.

The ‘getch()’ and ‘getche()’ functions were not adopted by other environments, such as *nix. Eventually, Microsoft elected to rename the functions with a leading underscore to help identify their proprietary (Microsoft) nature.

By the look of the error message, I assume that the ‘_getch()’ function has been adopted by the «ISO C++» standard. (However, I don’t do C++ as it is an abomination to many C programmers such as myself).

Note: The *nix ‘curses’ library also sports a getch() which is somewhat similar to the old Microsoft function.

The compiler warning noted in the question is just that; a warning. Most likely, code will still compile and run (in a Microsoft environment).

Понравилась статья? Поделить с друзьями:
  • Error c4996 fopen this function or variable may be unsafe
  • Error c4716 должна возвращать значение
  • Error c4703 используется потенциально неинициализированная локальная переменная указатель
  • Error c4700 использована неинициализированная локальная переменная
  • Error c4700 uninitialized local variable n used