为什么编译器在我定义_CRT_SECURE_NO_WARNINGS之后仍然警告我不安全的strtok?

时间:2014-01-10 12:16:04

标签: c++ strtok

我正在使用Visual Studio Express 2012 for Windows Desktop。

我总是收到错误

Error C4996: 'strtok': This function or variable may be unsafe.
  Consider using strtok_s instead.
  To disable deprecation, use _CRT_SECURE_NO_WARNINGS.
  See online help for details.

当我尝试构建以下内容时:

#include "stdafx.h"
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <cstring>
using namespace std;
int main() {
    char the_string[81], *p;
    cout << "Input a string to parse: ";
    cin.getline(the_string, 81);
    p = strtok(the_string, ",");
    while (p != NULL) {
        cout << p << endl;
        p = strtok(NULL, ",");
    }
    system("PAUSE");
    return 0;
}

为什么即使我定义_CRT_SECURE_NO_WARNINGS我也会收到此错误,我该如何解决?

4 个答案:

答案 0 :(得分:6)

由于预编译头文件(stdafx.h)的内容,您的#define不起作用。样板文件如下所示:

#pragma once
#include "targetver.h"
#include <stdio.h>
#include <tchar.h>

导致问题的是最后两个#includes,那些.h文件本身已经是#include string.h。因此你的#define太晚了。

除了在编译器设置中定义宏之外,简单的解决方法是将#define移动到stdafx.h文件中。修正:

#pragma once
#define _CRT_SECURE_NO_WARNINGS
#include "targetver.h"
#include <stdio.h>
#include <tchar.h>

答案 1 :(得分:4)

这可能是一个老帖子,但我最近遇到了类似的问题。 我进入了项目选项 - &gt; C / C ++ - &gt;预处理器 - &gt;将_CRT_SECURE_NO_WARNINGS添加到预处理程序定义列表中。 这样你就不必把它放在每个文件中。

答案 2 :(得分:0)

尝试以下操作。

#pragma warning (disable : 4996)

请注意错误编号为C4996。

答案 3 :(得分:-1)

看起来您打开了一个编译器选项,强制编译器将所有警告都视为错误。关闭此选项或确实使用宏_CRT_SECURE_NO_WARNINGS