0

I am quite new to c++ and learning it following a tutorial. But when it comes to debug, the debugger says ctime is unsafe. It says : C4996 'ctime': This function or variable may be unsafe. Consider using ctime_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. what does this mean? The same code works perfect in codeblock 17.12. How can I fix it in order to work in visual studio 2017?

#include<iostream>
#include<string>
#include<ctime>
#include<stdexcept>

using namespace std;

class FactorialException :public exception {
private: int n;
         char *dt;

public:
    FactorialException(int n) {
        this->n = n;
        time_t now = time(0);
        dt = ctime(&now);
    }

    const char * what() const throw () {
        return "Unable to calculate factorial of negative number";
    }
    int getValue() {
        return this->n;
    }
    char* getTime() {
        return dt;
    }
};

int factorial(int n) {
    int fact = 1;
    if (n < 0) {
        /*string strError = "Unable to calculate factorial or negative number";
        throw strError;*/
        FactorialException ex(n);
        throw ex;
    }
    for (int i = 1; i < n; ++i) {
        fact *= i;
    }
    return fact;
}

int main() {
    int n;
    bool error = false;
    do {
        try {
            error = false;
            cout << "Enter a Number: ";
            cin >> n;
            cout << factorial(n) << endl;
        }
        catch (FactorialException& ex) {
            cout << ex.what() << ", n = " << ex.getValue() << ", at time: " << ex.getTime() << endl;
            error = true;
        }
    } while(error);

    return 0;

}

psamead
  • 1
  • 2
  • 2
    There are several function in the standard C++ library (most (all?) originating with the standard C library) which are not re-entrant. Microsoft has made safe (albeit non-standard) versions of those routines, which usually require the caller to provide a state holding context. – Eljay Jun 11 '19 at 16:23
  • 1
    Neither have any. These are both IDEs (glorified text editors). Having said that, have you tried to read *To disable deprecation, use _CRT_SECURE_NO_WARNINGS* and, uh, I dunno, google it? – n. m. could be an AI Jun 11 '19 at 16:26
  • 1
    Duplicate? See here how to do it without CL.exe (the compiler used by Visual Studio) complaining: https://stackoverflow.com/questions/13550864/error-c4996-ctime-this-function-or-variable-may-be-unsafe – kuga Jun 11 '19 at 16:27
  • 4
    By the way, a C++ tutorial that tries to use `ctime` is probably either outdated or less than competent to begin with. – n. m. could be an AI Jun 11 '19 at 16:31
  • https://wiki.sei.cmu.edu/confluence/display/c/MSC24-C.+Do+not+use+deprecated+or+obsolescent+functions – Hans Passant Jun 11 '19 at 18:32
  • Thanks guys, How do I use ctime_s in this code to make it work? – psamead Jun 14 '19 at 18:33

0 Answers0