c++ - strtrok_s 函数不接受 2 个参数

标签 c++ visual-c++

//一个简单的程序,将空格和逗号解释为分隔符(单独的字符)

//并在其自己的行上打印每个子字符串(即每个标记):

#include "stdafx"
#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_s(the_string, ", ");
while (p != nullptr) {
cout << p << endl;
p = strtok_s(nullptr, ", ");

}


return 0;

}

这是它给我带来的问题 Error 1 error C2660: 'strtok_s' : function does not take 2arguments

IntelliSense:函数调用中的参数太少

最佳答案

编译器仅推荐更安全的 CRT 函数,如果您确实想使用原始 strtok 函数,它还会为您提供关闭警告的说明:

warning C4996: 'strtok': This function or variable may be unsafe. Consider
using strtok_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNING

只需在项目设置中添加_CRT_SECURE_NO_WARNING作为预处理器定义或添加到stdafx.h文件的顶部#define _CRT_SECURE_NO_WARNING 1

参见Security Features in the CRT

您显然对 C/C++ 非常陌生,因此您还不必担心这个细节。出现此警告的原因是许多可追溯到 Kernighan & Ritchie's original language 的长标准 C 字符串库函数。在现代恶意软件世界中存在一些固有的安全问题。因此,任何生产应用程序都应该避免偏爱“更安全的 CRT”版本。

特别是 strtok 通过在库中拥有内部隐藏状态来工作,有时可以利用它在解析器中造成安全问题。

char *strtok(char *str, const char *delim);

strtok_s 函数仅采用显式上下文变量来用于状态,而不是隐藏的内部变量。在所有其他方面,它的工作原理与 strtok 完全相同。

char *strtok_s(char *strToken, const char *strDelimit, char **context);

因此,您的代码将执行与书籍示例完全相同的操作,如下所示:

#include <iostream>
#include <cstring>
using namespace std;

int main(){

char the_string[81], *p;
char *next_token = nullptr;

cout << "Input a string to parse: ";
cin.getline(the_string, 81);
p = strtok_s(the_string, ", ", &next_token);
while (p != nullptr) {
cout << p << endl;
p = strtok_s(nullptr, ", ", &next_token);
}


return 0;
}   

有关 Safer CRT 的更多信息和历史记录,请参阅 Security Development Lifecycle (SDL) Banned Function Calls

关于c++ - strtrok_s 函数不接受 2 个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36393334/

相关文章:

c++ - 主窗口类外的连接槽

c++ - 奇怪的 Unresolved external 错误

c++ - 练习模板返回错误

c++ - C++ 或 VC++.net 中的套接字编程

C++访问冲突读取位置0xcdcdcdcd调用函数时出错

c++ - Valgrind : is there a memory leak in the output? 总结

c++ - SystemParametersInfoA 和 SystemParametersInfo 之间有什么区别?

c# - 使用/clr 编译现有的 C++ 代码,然后从 C# 调用它

c++ - 奇怪的 boolean 值

C++ std::tr1::hash::operator() 未定义?