Solved

How is it possible to convert a 'string' variable to a 'LPCTSTR' variable?

Posted on 2001-08-07
15
358 Views
Last Modified: 2008-02-01
Greetings:

In my program I need to perform various 'string' operations to create a specific string.  Afterwards, this string needs to be used in a function which takes a 'LPCTSTR' parameter.

How can I convert the 'string' into a variable of type 'LPCTSTR'?

The assingment I'm attempting looks like this:

string StringFileName;
LPCTSTR pstrLocalFile;

...
...
pstrLocalFile = StringFileName;
...

The error I'm getting is:

error C2679: binary '=' : no operator defined which takes a right-hand operand of type 'class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >
0
Comment
Question by:John500
15 Comments
 
LVL 6

Expert Comment

by:JonFish85
Comment Utility
try this maybe:

pstrLocalFile = (LPCTSTR)StringFileName;

hope this helps!
0
 
LVL 30

Expert Comment

by:Axter
Comment Utility
pstrLocalFile = StringFileName.c_str();
0
 

Author Comment

by:John500
Comment Utility
JonFish85,

I did that, and got this:

error C2440: 'type cast' : cannot convert from 'class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >' to 'const char *'
        No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
0
 

Expert Comment

by:sindbad
Comment Utility

Try,

pstrLocalFile = (LPCTSTR) StringFileName.c_str();

0
 
LVL 22

Expert Comment

by:nietod
Comment Utility
Axter (and also sinbad) is right about how to get it to compiler.

BUT you need to make sure to use it correctly.  the c_str()  member function returns a pointer to a temporarily allocated NUl-terminated string.   This string may be deleted or may be changed the next time a non-constant member function is called on the string object.  This includes the string object's destructor.  that means that the pointer returned is of a temporary nature.  You cannot save that point and use it later (long later).  you must use the pointer (almost) immediately and then not use it.  Once the string has had the opportunity to change, that pointer is not valid.  for example

char *F()
{
   const char *ptr;
   char c;
   string S = "ABC";

   ptr = S.c_str();
   cout << ptr; // okay
   c = *ptr; //  okay;
   S[0] = '1'; // String has been changed, pointer is not    valid.
   cout << ptr; // DANGER ERROR.

   return ptr; // ERROR even if string hadn't been
            // changed. here it will be destroyed
            // so pointer is not valid.
}
0
 
LVL 4

Expert Comment

by:AssafLavie
Comment Utility
"pstrLocalFile = (LPCTSTR) StringFileName.c_str();"

This is useless.
If you're in Unicode it's not going to compile. If your not, you're casting a 'const char*' into a 'const char*'...
0
 
LVL 22

Expert Comment

by:nietod
Comment Utility
Just to clarify, that.  It is the cast that is useless--actually more "dangerious", not the technique of calling c_str().   That part is fine
0
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 9

Expert Comment

by:jasonclarke
Comment Utility
I think it's the fact that a TCHAR string is being used that is useles...

something like this is needed:

USES_CONVERSION;
string StringFileName;
LPCTSTR pstrLocalFile;
pstrLocalFile = A2CT(StringFileName.c_str());
0
 
LVL 22

Expert Comment

by:nietod
Comment Utility
That would be the safest. But maybe overkill if you don't plan on supporting unicode.   The problem with the original is that it you ever did change your mind and support unicode, the code would still compile and then work wrong.
0
 
LVL 1

Expert Comment

by:MattC
Comment Utility
what about CString??
0
 

Author Comment

by:John500
Comment Utility
nietod,

This will be a fairly simple program of opening an FTP session and transfering a file.  

I'll need to accept a command line parameter and pass that parameter to the LPCTSTR variable.  Since you say the pointer must be used "(almost) immediately", wouldn't you agree that the following sequence will work fine:

#include <afxinet.h>


void FTPConnect(LPCTSTR pstrLocalFile)
{
    LPCTSTR pstrRemoteFile "some directory";
...
PutFile(pstrLocalFile, pstrRemoteFile, ...);
...
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    string StringFileName;

    StringFileName = lpCmdLine;
    pstrLocalFile = FTPFileName.c_str();

    FTPConnect();
    ...
}

0
 

Author Comment

by:John500
Comment Utility
nietod,

My last comment should have shown the FTPConnect function taking a parameter within main():

FTPConnect(pstrLocalFile);

Also, to reiterate, the reason I don't just assign the command line parameter (type LPSTR) to the LPCTSTR variable (which will work) is because I need to first test the command line string and add to it a directory path.  Since I can't easily add these strings, I first manipulate the string and then assign it to the LPCTSTR.


   
0
 
LVL 22

Accepted Solution

by:
nietod earned 50 total points
Comment Utility
That is sage because the strig object is not ever altered in the code.  The only time it is "altered" is when it is destroyed at the end of the function and you are done using it at that time.

If you did something like

   string StringFileName;

   StringFileName = lpCmdLine;
   pstrLocalFile = StringFileName.c_str();
   
   StringFileName += " "; // alter string.

   FTPConnect(pstrLocalFile); // ERROR.

that would be a problem.


However, a slightly safer approach is

FTPConnect(StringFileName.c_str());

This never stores the pointer to the c-string.  This is safest because the pointer is only used when the FTPConnect function is used and durring this period of time it is impossible for the string object to change.  So there is almost no chance of making an accidental mistake that way.  You could add code that does change hte strign object, yet this code would still be safe.
0
 

Author Comment

by:John500
Comment Utility
Ok great!
0
 
LVL 22

Expert Comment

by:nietod
Comment Utility
Thanks, although it was really Axter that 1st suggested the solution.  
0

Featured Post

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

Often, when implementing a feature, you won't know how certain events should be handled at the point where they occur and you'd rather defer to the user of your function or class. For example, a XML parser will extract a tag from the source code, wh…
Introduction This article is a continuation of the C/C++ Visual Studio Express debugger series. Part 1 provided a quick start guide in using the debugger. Part 2 focused on additional topics in breakpoints. As your assignments become a little more …
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now