简体   繁体   中英

strtrok_s function does not take 2 arguments

// A simple program that interprets spaces and commas as delimeters (seperate characters)

// and prints each substring-that is, each token-on its own line:

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

}

This are the problems it gives me Error 1 error C2660: 'strtok_s' : function does not take 2 arguments

IntelliSense: too few arguments in function call

The compiler is only recommending the Safer CRT functions, and it also gives you instructions for turning off the warnings if you really want to use the original strtok function:

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

Just add _CRT_SECURE_NO_WARNING as a Preprocessor Define in your project settings or add to the top of your stdafx.h file #define _CRT_SECURE_NO_WARNING 1

See Security Features in the CRT

You are clearly very new to C/C++, so you don't need to worry about this detail just yet. The reason this warning is here is because many of the long-standard C string library functions that date back to Kernighan & Ritchie's original language have some inherent security problems in the modern world of malware. As such, any production application should avoid them favor of the "Safer CRT" versions.

In particular strtok works by having internal hidden state in the library, which can sometimes be exploited to create security problems in parsers.

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

The strtok_s function simply takes an explicit context variable to use for the state instead of the hidden internal variable. It works exactly the same as strtok in all other ways.

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

Therefore, your code would do exactly the same thing as your book sample as follows:

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

For more information and history on the Safer CRT, see Security Development Lifecycle (SDL) Banned Function Calls

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM