Environment variables are in char *, how to get it in std :: string

I am extracting environment variables in win32 using GetEnvironmentStrings() . It returns char* .

I want to find this line (char pointer) for a specific environment variable (yes, I know I can use GetEnvironmentVariable() , but I do it this way because I also want to print all the environment variables in the console as well - I just messed around) .

So, I thought that I would convert char* to std :: string and use find on it (I know that I can also use the c_string search function, but I'm more concerned about trying to copy char* to std::string ). But the following code does not seem to copy all char* to std::string (this makes me think that char* has the \0 character, but this is actually not the end).

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

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

+6
source share
6 answers

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

This is for regular C-lines, however GetEnvironmentStrings() returns a slightly strange format and you 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"; } 
+8
source

sizeof(a) in what you above will return the size of char* , i.e. a pointer (usually 32 or 64 bits). You searched for the strlen function there. And this is not required at all:

 std::string b(a); 

should be enough to get the first pair of environment variables.

+1
source

Are the following issues occurring?

 char* a = GetEnvironmentStrings(); string b; b=a; printf( "%s", b.c_str() ); 
0
source

When you speak:

 string b = string(a, sizeof(a)); 

you get a size a, which is a pointer and probably 4. So you get the first 4 characters. I'm not sure what you are actually trying to do, but you should just say:

 string b( a ); 
0
source
 char* a = ...; string str(a); string b; b = a; 
0
source

I assume that you mean the Windows API function GetEnvironmentStrings . So, check the result on nullptr and do a simple assignment:

 char* env = ::GetEnvironmentStrings(); if (0 != env) { std::string senv = env; // use senv to find variables } else { // report problem or ignore } 
0
source

Source: https://habr.com/ru/post/890335/


All Articles