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 !