如何解决编译器错误:“'strtok'函数可能不安全”

时间:2019-06-01 13:21:51

标签: c++ string.h

我目前正在编写一个程序,该程序可以转换几个数学函数,例如将浮点数转换为余弦,自然对数等。我还提供了一种将日期格式m/dd/yyyy转换为格式的方法mm-dd-yyyy中的。我试图用'/'标记c字符串,然后将其与'-'串联在一起。问题是Visual Studio给我一个C4996错误代码,并说我的功能可能不安全。我知道我可以将其关闭,以便它们不会向我发出此类警告,但是当我运行该程序时,strtok函数似乎没有任何作用。

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

//KEEP IN MIND THIS IS ONLY ONE PART OF THE PROGRAM, I have more includes, and this is under the main function. (I only included relevant includes)

//If they enter 4 to convert a cstring date.
    if (input == 4) {
        cout << "You entered: change the format of a cstring date" << endl;
        cout << "Please enter a date in the format of mm/dd/yyyy: " << endl;
        char str[12];   //C-String to hold input
        cin >> str;
        //Create an char[] to hold the answer
        char newStr[32];
        // Returns first token  
        char* token = strtok(str, "/");
        // Keep printing tokens while one of the 
        // delimiters present in str[]. 
        while (token != NULL)
        {
            strcat_s(newStr, token);    //Cat it to string
            strcat_s(newStr, "-");  //Add the -
            token = strtok(NULL, "/");
        }

        cout << "Your new Date is: " << newStr;
        return 0;
    }

即使我绕过错误消息并运行程序,也请输入例如:11/22/3333我收到11/22/3333的输出

0 个答案:

没有答案