Solved

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

Posted on 2001-08-07
15
392 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
15 Comments
 
LVL 6

Expert Comment

by:JonFish85
ID: 6361187
try this maybe:

pstrLocalFile = (LPCTSTR)StringFileName;

hope this helps!
0
 
LVL 30

Expert Comment

by:Axter
ID: 6361193
pstrLocalFile = StringFileName.c_str();
0
 

Author Comment

by:John500
ID: 6361201
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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Expert Comment

by:sindbad
ID: 6361281

Try,

pstrLocalFile = (LPCTSTR) StringFileName.c_str();

0
 
LVL 22

Expert Comment

by:nietod
ID: 6361305
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
ID: 6361469
"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
ID: 6361629
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
 
LVL 9

Expert Comment

by:jasonclarke
ID: 6363092
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
ID: 6363515
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
ID: 6365126
what about CString??
0
 

Author Comment

by:John500
ID: 6368068
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
ID: 6368159
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
ID: 6368193
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
ID: 6368591
Ok great!
0
 
LVL 22

Expert Comment

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

Featured Post

On Demand Webinar - Networking for the Cloud Era

This webinar discusses:
-Common barriers companies experience when moving to the cloud
-How SD-WAN changes the way we look at networks
-Best practices customers should employ moving forward with cloud migration
-What happens behind the scenes of SteelConnect’s one-click button

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

What is C++ STL?: STL stands for Standard Template Library and is a part of standard C++ libraries. It contains many useful data structures (containers) and algorithms, which can spare you a lot of the time. Today we will look at the STL Vector. …
Container Orchestration platforms empower organizations to scale their apps at an exceptional rate. This is the reason numerous innovation-driven companies are moving apps to an appropriated datacenter wide platform that empowers them to scale at a …
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.

726 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