3

I am writing a little app that uses SMTP.

And I got a weird error:

identifier "Luservar" is undefined`

code:

o_smtp->BodyText = _T(uservar->get_h().c_str() + ":" + pass_str.c_str() + "\n" + get_mac().c_str());

Why is it saying Luservar if i say uservar?

I have tried:

o_smtp->BodyText = uservar->get_h().c_str() + ":" + pass_str.c_str() + "\n" + get_mac().c_str();

But then I get a error like this: expression must have integral or unscoped enum type

I am fairly new to C++ and maybe its the wrong way to merge strings?

Joel Bodenmann
  • 2,152
  • 2
  • 17
  • 44

1 Answers1

4
  • DO NOT USE _T or TEXT(). Yegods.
  • If you're writing C++ (with classes and objects, and using types from the STL and C++'s standard library), then you shouldn't be writing C (by using typedefs, structs and raw pointers).
    • Remember that C++ and C are different languages despite their syntactic similarities and C++'s heritage in C.
    • Fun fact: Microsoft's VisualC++ is not a C compiler - it only supports the parts of C needed to compile C++: Does Visual Studio 2017 fully support C99?
    • What I mean by this is that if you're using std::string then you should not use .c_str() unless you really have to - and in this case, you don't have to (well, not for string-concatenation at least).

As for your code...

  • I assume these variables and function return-values are typed as std::string:
    • uservar->get_h()
    • pass_str
    • get_mac()
  • I assume that o_smtp->BodyText is typed as char*.
  • I assume that you simply want a concatenate those strings together, along with the literals in your C++ code.
    • In which case, let std::string do the concatenation for you!
std::string bodyText = uservar->get_h() + ":" + pass_str + "\n" + get_mac();

o_smtp->BodyText = bodyText.c_str();

However you need to be careful about the lifetime of std::string bodyText - as soon as bodyText leaves scope then its c_str expires. See this thread: What is std::string::c_str() lifetime?

Remember that bodyText.c_str() provides a char* view of bodyText (i.e. it's a different representation of the same chunk of memory), rather than a copy of clone or bodyText, so if o_smtp->BodyText is long-life'd then you'll need to ensure bodyText has the same lifetime as o_smtp or copy bodyText's character buffer to a separate buffer that will live long enough - or determine if o_smtp will take ownership of its BodyText character buffer.

Dai
  • 141,631
  • 28
  • 261
  • 374