1

I am trying to store some contents into a string variable by passing it as a parameter in various types of Windows API functions which accepts variable like char *.

For example, my code is:-

std::string myString;
GetCurrentDirectoryA( MAX_PATH, myString );

Now how do I convert the string variable to LPSTR in this case.

Please see, this function is not meant for passing the contents of string as input, but the function stores some contents into string variable after execution. So, myString.c_str( ) is ruled out.

Edit: I have a workaround solution of removing the concept of string and replacing it with something like

char myString[ MAX_PATH ];

but that is not my objective. I want to make use of string. Is there any way possible?

Also casting like

GetCurrentDirectoryA( MAX_PATH, ( LPSTR ) myString );

is not working.

Thanks in advance for the help.

3 Answers 3

7

Usually, people rewrite the Windows functions they need to be std::string friendly, like this:

std::string GetCurrentDirectoryA()
{
  char buffer[MAX_PATH];
  GetCurrentDirectoryA( MAX_PATH, buffer );
  return std::string(buffer);
}

or this for wide char support:

std::wstring GetCurrentDirectoryW()
{
  wchar_t buffer[MAX_PATH];
  GetCurrentDirectoryW( MAX_PATH, buffer );
  return std::wstring(buffer);
}
Sign up to request clarification or add additional context in comments.

Comments

2

LPTSTR is defined as TCHAR*, so actually it is just an ordinary C-string, BUT it depends on whether you are working with ASCII or with Unicode in your code. So do

LPTSTR lpStr = new TCHAR[256];
ZeroMemory(lpStr, 256);
//fill the string using i.e. _tcscpy
const char* cpy = myString.c_str();
_tcscpy (lpStr, cpy);
//use lpStr

See here for a reference on _tcscpy and this thread.

2 Comments

Hi, did you mean .c_str( ) or is there something like .c_star( ). I am not able to search it. Also, I am using ASCII. So, according to my edited question, is the workaround solution given by me better or do you recommend me to use your proposed solution. Please can you contrast both the methods to me.
It was the autocorrect of my tablet! I do mean c_str() of course! I use the generic approach which is common. In order to preserve genericity my approach is better. If you are fine with your approach then use it, as it provides a simpler, but non-generic way.
1

Typically, I would read the data into a TCHAR and then copy it into my std::string. That's the simplest way.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.