c++winapicstring

Environment Variables are in a char* how to get it to a std::string


I am retrieving the environment variables in win32 using GetEnvironmentStrings(). It returns a char*.

I want to search this string(char pointer) for a specific environmental variable (yes I know I can use GetEnvironmentVariable() but I am doing it this way because I also want to print all the environment variables on the console aswell - I am just fiddling around).

So I thought I would convert the char* to an std::string & use find on it (I know I can also use a c_string find function but I am more concerned about trying to copy a char* into a std::string). But the following code seems to not copy all of the char* into the std::string (it makes me think there is a \0 character in the char* but its not actually the end).

char* a = GetEnvironmentStrings();
string b = string(a, sizeof(a));
printf( "%s", b.c_str() );  // prints =::= 

Is there a way to copy a char* into a std::string (I know I can use strcpy() to copy a const char* into a string but not a char*).


Solution

  • You do not want to use sizeof() in this context- you can just pass the value into the constructor. char* trivially becomes const char* and you don't want to use strcpy or printf either.

    That's for conventional C-strings- however GetEnvironmentStrings() returns a bit of a strange format and you will probably need to insert it manually.

    const char* a = GetEnvironmentStrings();
    int prev = 0;
    std::vector<std::string> env_strings;
    for(int i = 0; ; i++) {
        if (a[i] == '\0') {
            env_strings.push_back(std::string(a + prev, a + i));
            prev = i;
            if (a[i + 1] == '\0') {
                break;
            }
        }
    }
    for(int i = 0; i < env_strings.size(); i++) {
        std::cout << env_strings[i] << "\n";
    }