Search code examples
c++visual-c++visual-studio-2012environment-variablessetenv

C++: Setenv(). Undefined identifier in Visual Studio


Look my code seems to be correct, according to all the documentation I can find online. My IDE is MS Visual Studio Xpress 4 Windows Desktop 2012, and it's compiler is throwing up the error:

Error 1 error C3861: 'setenv': identifier not found e:\users\owner\documents\visual studio 2012\projects\project1\project1\source1.cpp 18 1 Project1.

Help me!!!

#include <windows.h>
#include <sstream>
#include <ostream>
#include <cstdlib>
#include <iostream>
#include <stdlib.h>

using namespace std;

int howManyInClass = 0;
int main(){

long checklength = sizeof(getenv("classSize"))/sizeof(*getenv("classSize"));
if (checklength==0){
    cout<<"Please enter the ammount of students in your class";
    cin>> howManyInClass;
    cin.ignore();
    setenv("classSize", howManyInClass, 1);}

};

Solution

  • You can either use _putenv() which takes a string parameter as the string classSize=7;

    ostringstream classSize;
    classSize << "classSize=" << howManyInClass;
    _putenv(classSize.str().c_str());
    

    ...or (preferably) the security enhanced _putenv_s() that takes the key and the value as separate (const char*) parameters;

    ostringstream classSize;
    classSize << howManyInClass;
    _putenv_s("classSize", classSize.str().c_str());