个性化阅读
专注于IT技术分析

如何解决C++错误C4996’getch’:不建议使用此项目的POSIX名称。而是使用符合ISO C和C ++的名称:_getch

对于使用C ++的新手来说, 使用现代工具可能会让人头疼, 特别是在学校的VS版本很旧并且你在家中拥有最新版本的VS时。对于学生而言, 最著名的练习之一就是用这种语言着称的世界。使用控制台应用程序, 练习很简单, 打印” hello world”并保持控制台打开以查看打印的消息。根据你老师的编程风格, 你可能会使用cout收到一个示例片段:

#include <iostream>
#include <conio.h>

using namespace std;

void main(void)
{
	cout << "Hello World" << endl;

	getch();
}

或使用printf在控制台中打印文本:

#include <iostream>
#include <conio.h>

void main(void)
{
	printf("Hello World");

	getch();
}

这两个脚本都是完全有效的, 并且它们使用getch方法保持控制台打开。它们应该在VS总是过时的学校的编译器中正常工作, 但是, 如果你使用现代的编译器来编译任何先前的示例(使用Visual Studio的最新版本), 你将面临异常。问题在于getch方法是一个非标准函数, MS编译器传统上以两种名称提供这些名称, 但是Microsoft决定在不使用下划线的情况下定义名称, 因为这些名称仅供程序员使用。

此问题最简单的解决方法是使用_getch方法, 并在下划线作为前缀:

#include <iostream>
#include <conio.h>

using namespace std;

void main(void)
{
	cout << "Hello World" << endl;

	// Use the getch method with a prefixed underscore
	_getch();
}

此方法的工作原理相同, 但不会被视为不赞成使用。你还可以使用std名称空间的cin.get方法:

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

编码愉快!

赞(0)
未经允许不得转载:srcmini » 如何解决C++错误C4996’getch’:不建议使用此项目的POSIX名称。而是使用符合ISO C和C ++的名称:_getch

评论 抢沙发

评论前必须登录!