CSTRING Management (About all operations of CString, such as char * to cstring conversion, etc., strongly recommended)

zhaozj2021-02-08  204

CString Management

CStrings are a useful data type. They greatly simplify a lot of operations in MFC, making it much more convenient to do string manipulation. However, there are some special techniques to using CStrings, particularly hard for people coming a pure-C background from to Learn. This Essay Discusses Some of these Techniques.

.

CString concatenation Formatting (including integer-to-CString) Converting CStrings to integers Converting between char * to a CString char * to CString CString to char * I: Casting to LPCTSTR CString to char * II: Using GetBuffer CString to char * III: Interfacing To a control cstring to bstr Bstr to CString (30-JAN-01) Variant to CString (24-Feb-01) Loading StringTable Resources (22-Feb-01) CStrings and Temporary Objects CString Efficiency

String concatenation

One of the Very Convenient Features of Cstring Is The Ability To Concatenate Two Strings. For Example IF WE HAVE

CSTRING GRAY ("Gray");

CString cat ("cat");

CSTRING GRAYCAT = GRAY CAT;

Is a lot nicer Than Having to do Something Like:

Char gray [] = "gray";

CHAR CAT [] = "CAT";

Char * graycat = malloc (Strlen Strlen (CAT) 1);

STRCPY (Graycat, Gray);

STRCAT (GRAYCAT, CAT);

Formatting (Including Integer-to-CString)

Rather Than Using Sprintf or Wsprintf, You Can Do Formatting for a cstring by using the format method:

CString S;

S.Format (_T ("Total IS% D"), TOTAL);

The advantage here is that you do not have to worry about whether or not the buffer is large enough to hold the formatted data; this is handled for you by the formatting routines.Use of formatting is the most common way of converting from non- String Data Types to a cstring, for example, converting an integer to a cstring:

CString S;

S.Format (_T ("% D"), TOTAL);

I always use the the the purpose of _t () is to compile a string for an 8-bit-character Application AS :

#define _t (x) x // non-unicode version

Whereas for a Unicode Application IT Is Defined AS

#define _t (x) l ## x // unicode Version

SO in Unicode The Effect Is as if i had write

S.Format (l "% d", total);

If you ever think you might ever possibly use Unicode, start coding in a Unicode-aware fashion. For example, never, ever use sizeof () to get the size of a character buffer, because it will be off by a factor of 2 in A Unicode Application. WE Cover Unicode In Some Detail in Win32 Programming. When I Need A Size, I Have A Macro Called Dim, Which IS Defined in A File Dim.h That I include Everywhere:

#DEFINE DIM (X) (SizeOf ((x)) / sizeof ((x) [0]))

This Is Not Only Useful for Dealing with Unicode Buffers Whose Size Is Fixed At Compile Time, But Any Compile-Time Defined Table.

Class whatver {...};

WhatVER DATA [] = {

{...},

...

{...},

}

For (int i = 0; i

BEWARE OF THOSE API Calls That Want Genuine Byte Count Will NOT WORK.

TCHAR DATA [20];

LSTRCPYN (Data, Longstring, Sizeof (DATA) - 1); // Wrong!

LSTRCPYN (Data) - 1); // RightWriteFile (F, Data, DIM (DATA), & BYTESWRITTEN, NULL); // WRONG!

Writefile (F, Data, Sizeof (Data), & Byteswritten, NULL); // Right

This is because lstrcpyn wants a character count, but WriteFile wants a byte count. Also note that this always writes out the entire contents of data. If you only want to write out the actual length of the data, you would think you might do

Writefile (F, Data), & Byteswritten, NULL); // WRONG

But That Will Not Work In A Unicode Application. Instead, You Must Do

Writefile (F, Data) (DATA) * SIZEOF (TCHAR), & BYTESWRITEN, NULL; // Right

because WriteFile wants a byte count. (For those of you who might be tempted to say "but that means I'll always be multiplying by 1 for ordinary applications, and that is inefficient", you need to understand what compilers actually do. No real C or C compiler would actually compile a multiply instruction inline; the multiply-by-one is simply discarded by the compiler as being a silly thing to do And if you think when you use Unicode that you'll have to pay the cost. of multiplying by 2, Remember That Is Just A Bit-Shift Left by 1 Bit, Which The Compiler Is Also Happy To Do Instead of The Multiplication.

Using _T does not create a Unicode application It creates a Unicode-aware application When you compile in the default 8-bit mode, you get a "normal" 8-bit program;.. When you compile in Unicode mode, you get a Unicode (16-bit-character) Application. Note That A CSTRING IN A Unicode Application IS A String That Holds 16-bit Characters.

Converting a cstring to an anteger

The simplest way to convert a CString to an integer value is to use one of the standard string-to-integer conversion routines.While generally you will suspect that _atoi is a good choice, it is rarely the right choice. If you play to be unicode-ready, you should call the function _ttoi, which compiles into _atoi in ANSI code and _wtoi in unicode code. you can also consider using _tcstoul (for unsigned conversion to any radix, such as 2, 8, 10 or 16) or _tcstol For Signed Conversion To Any Radix. for Example, Here Area Some Examples:

CSTRING HEX = _T ("fab");

CSTRING DECIMAL = _T ("4011");

Assert (_TCSTOUL (HEX, 0, 16) == _ttoi (decimal));

Converting Between Char * and CString

This is the most common set of questions beginners have on the CString data type. Due largely to serious C magic, you can largely ignore many of the problems. Things just "work right". The problems come about when you do not understand the Basic Mechanisms and the Don't Understand Why Something That Seem Obvious Doesn't Work.

For Example, Having Noticed The Above Example You Might Wonder Why You Can't Write

CSTRING graycat = "gray" "cat";

oral

CSTRING GRAYCAT ("Gray" "CAT");

In fact the compiler will complain bitterly about these attempts. Why? Because the operator is defined as an overloaded operator on various combinations of the CString and LPCTSTR data types, but not between two LPCTSTR data types, which are underlying data types. You can 'T Overload C Operators on base type like intid and char, or char *. What Will Work IS

CString graycat = cstring ("gray" cstring ("cat");

OR Even

CString graycat = cstring ("gray") "cat"; if you stop, you..

Char * to cstring

SO You Have a char *, or a string. How do you create a cstring. Here Are Some Examples:

Char * p = "this is a test"

OR, in Unicode-aware Applications

TCHAR * P = _t ("this is a test")

oral

LPTSTR P = _t ("this is a test");

You can write any of the folload:

CString s = "this is a test"; // 8-bit only

CString s = _t ("this is a test"); // unicode-aware

CString S ("This Is A Test"); // 8-bit Only

CString S (_T ("this is a test"); // unicode-aware

CString s = P;

CString S (p);

Any of these Readily Convert the constant string or the pointer to a cstring value. Note That The Characters Assigned Area, Copied Into the Cstring So That You Can do Something Like

TCHAR * P = _t ("gray");

CString S (p);

P = _t ("cat");

S = P;

And Be Sure That The resulting string is "graycat".

..................... ..

CString to Char * i: casting to lpctstr

THIS A Slightly Harder Transition To Find Out About, and There Is Lots of Confusion About The "Right" Way to Do It. There Are Quite A Few Right Ways, And Probably An Equal Number of Wrong Ways.

The first thing you have to understand about a CString is that it is a special C object which contains three values:. A pointer to a buffer, a count of the valid characters in the buffer, and a buffer length The count of the number of characters can be any size from 0 up to the maximum length of the buffer minus one (for the NUL byte). The character count and buffer length are cleverly hidden.Unless you do some special things, you know nothing about the size of the buffer that is associated with the CString. Therefore, if you can get the address of the buffer, you can not change its contents. you can not shorten the contents, and you absolutely must not lengthen the contents. This leads to some at-first-glance odd Workarounds.

The operator LPCTSTR (or more specifically, the operator const TCHAR *), is overloaded for CString. The definition of the operator is to return the address of the buffer. Thus, if you need a string pointer to the CString you can do something like

CSTRING S ("graycat");

LPCTSTR P = S;

. And it works correctly This is because of the rules about how casting is done in C; when a cast is required, C rules allow the cast to be selected For example, you could define (float) as a cast on a complex number. (a Pair of floats) and define it to return only the first float (Called the "real part") of the complex number so you could Say

Complex C (1.2F, 4.8F);

FLOAT REALPART = C;

And Expect to see, if the the value of realpart is now 1.2.

This works for you in all kinds of places For example, any function that takes an LPCTSTR parameter will force this coercion, so that you can have a function (perhaps in a DLL you bought):. BOOL DoSomethingCool (LPCTSTR s);

And Call IT As Follows

CSTRING FILE ("C: // myfiles // coolstuff")

Bool Result = DOSMETHINGCOOL (File);

This works correctly because the DoSomethingCool function has specified that it wants an LPCTSTR and therefore the LPCTSTR operator is applied to the argument, which in MFC means that the address of the string is returned.

But what if you want to format it?

CSTRING GRAYCAT ("graycat");

CString S;

S.Format ("MEW! I Love% S", graycat;

Note That Because The Value Appers in The Variable-Argument List (The Specification Of The Function) That There Is No Implicit Coercion Operator. What Are you going to get?

Well, Surprise, You Actually Get The String

"MEW! I Love Graycat"

because the MFC implementers carefully designed the CString data type so that an expression of type CString evaluates to the pointer to the string, so in the absence of any casting, such as in a Format or sprintf, you will still get the correct behavior. The Additional Data That Describes a CString Actually Lives in The Addresses Below The Nominal Cstring Address.

What You can't do is modify the string. For example, you might try to do something "." "By a" (DON 'THIS WAY, You Should Use The National Language Support Features for Decimal Conversions if You Care About Internationalization, But this makes a Simple Example:

CString V ("1.00"); // Currency Amount, 2 Decimal Places

LPCTSTR P = V;

P [LSTRLEN (P) - 3] = ',';

If you try to do this, The Compiler Will Complain That You are assigning to a constant string. This is the correct message. It Would Also Complain if you tried

STRCAT (P, "EACH");

BECAUSE STRCAT WANTS An LPTSTR AS ITS First Argument and you gave it an lpctstr.

Don't try to defeat these error messages. You will get yourself Into Trouble!

The reason is that the buffer has a count, which is inaccessible to you (it's in that hidden area that sits below the CString address), and if you change the string, you will not see the change reflected in the character count for the buffer. Furthermore, if the string happens to be just about as long as the buffer physical limit (more on this later), an attempt to extend the string will overwrite whatever is beyond the buffer, which is memory you have no right to write ( Right?) And You'll Damage Memory You Don't OWN. Sure Recipe for a dead application.

CString to Char * II: Using GetBuffer

A special method is available for a CString if you need to modify it. This is the operation GetBuffer. What this does is return to you a pointer to the buffer which is considered writeable. If you are only going to change characters or shorten the string You are now free to do so:

CString S (_T ("file.ext"));

LPTSTR P = S.GetBuffer ();

LPTSTR DOT = STRCHR (p, '.'); // OK, Should Have Used S.Find ...

IF (p! = null)

* p = _t ('/ 0');

S.ReleaseBuffer ();

This is the first and simplest use of GetBuffer You do not supply an argument, so the default of 0 is used, which means. "Give me a pointer to the string; I promise to not extend the string". When you call ReleaseBuffer , the actual length of the string is recomputed and stored in the CString Within the scope of a GetBuffer / ReleaseBuffer sequene, and I emphasize this:. you Must Not, Ever, Use Any Method of CString on the CString whose buffer you have The! Reason for this is what the the integrity of the cstring object is not Guaranteed Until The ReleaseBuffer IS Called. Study The code Below: CString s;

LPTSTR P = S.GetBuffer ();

// ... LOTS of Things happen via the Pointer P

INT n = s.getlength (); // bad !!!!! Probably will Give Wrong Answer !!!

S.trimright (); // bad !!!!! No Guarantee IT Will Work !!!!

S.releaseBuffer (); // Things Are Now OK

INT m = s.getlength (); // this is Guaranteed to Be Correct

S.trimright (); // Will Work Correctly

Suppose You Want to Actually Extend The String. In this case you must know how large the string will get. This is just like declaring

Char buffer [1024];

Knowing That 1024 is more Thanugh Space for anything you are going to do. The equivalent in the cstring world is

LPTSTR P = S.GetBuffer (1024);

...................................

Also, note that if you have a pointer to a const string, the string value itself is stored in read-only memory; an attempt to store into it, even if you've done GetBuffer, you have a pointer to read-only memory , so an attempt to store into the string will fail with an access error. I have not verified this for CString, but I've seen ordinary C programmers make this error frequently.A common "bad idiom" left over from C programmers is To Allocate a Buffer of Fixed Size, Do A Sprintf Into IT, And Assign It To A CString:

Char buffer [256];

Sprintf (buffer, "% ...", args, ...); // ... Means "LOTS of Stuff Here"

Cstring s = buffer;

While The Better Form Is To DO

CString S;

S.Format (_T ("% ....", args, ...);

Note That this always; if your string happens to end up longer Than 256 Bytes you don't clobber the stack!

Another Common Error Is To Be Clever And Realize That A Fixed Size Won't work, so the program, this is each, one is is Even Sillier:

INT LEN = LSTRLEN (PARM1) 13 LSTRLEN (PARM2) 10 100;

Char * buffer = new char [len];

Sprintf (Buffer, "% s is equals to% s, valid data", parm1, parm2);

Cstring s = buffer;

....

DELETE [] BUFFER;

WHERE IT CAN Be Easily Written As

CString S;

S.Format (_T ("% s is equals to% s, valid data"), PARM1, PARM2;

Note that the sprintf examples are not Unicode-ready (although you could use tsprintf and put _T () around the formatting string, but the basic idea is still that you are doing far more work than is necessary, and it is error-prone.

CString to Char * III: Interfacing to a Control

A very common operation is to pass a CString value in to a control, for example, a CTreeCtrl. While MFC provides a number of convenient overloads for the operation, but in the most general situation you use the "raw" form of the update, And Therefore you need to store a Pointer to a string in the TVItem systemstruct: TVINSERTITEMSTRUCT: TVINSERTITEMSTRUCT TVI;

CString S;

// ... Assign Something to S

TVi.Item.psztext = s; // compiler Yells at you here

// ... Other stuff

HtreeItem Ti = C_Mytree.InsertItem (& TVI);

?! Now why did the compiler complain It looks like a perfectly good assignment But in fact if you look at the structure, you will see that the member is declared in the TVITEM structure as shown below:

LPTSTR PSZTEXT;

Int cchtextmax;

. ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,

Ok, you say, i can deval with what, and you write

TVi.Item.psztext = (lpctstr) s; // compiler still complains!

What the compiler is now complaining about is that you are attempting to assign an LPCTSTR to an LPTSTR, an operation which is forbidden by the rules of C and C . You may not use this technique to accidentally alias a constant pointer to a non-constant alias so you can violate the assumptions of constancy. If you could, you could potentially confuse the optimizer, which trusts what you tell it when deciding how to optimize your program. For example, if you do

Const int I = ...;

// ... do Lots of Stuff

... = a [i]; // USAGE 1

// ... LOTS More Stuff

... = a [i]; // USAGE 2

Then the compiler can trust that, because you said const, that the value of i at "usage1" and "usage2" is the same value, and it can even precompute the address of a [i] at usage1 and keep the value around for Later Use at usage2, Rather Than computing it each time. if you get able to write writeconst int i = ...

INT * P = & I;

// ... do Lots of Stuff

... = a [i]; // USAGE 1

// ... LOTS More Stuff

(* p) ; // Mess over compiler's associum

// ... and other stuff

... = a [i]; // USAGE 2

The the compiler would believe in the constancy of i, and consequently the constancy of the location of a [i], and the place where the indirection is done destroys that assumption. Thus, the program would exhibit one behavior when compiled in debug mode ( no optimizations) and another behavior when compiled in release mode (full optimization). This Is Not Good. Therefore, the attempt to assign the pointer to i to a modifiable reference is diagnosed by the compiler as being bogus. This is why the (LPCTSTR ) Cast Won't really help.

Why not just declare the member as an LPCTSTR? Because the structure is used both for reading and writing to the control. When you are writing to the control, the text pointer is actually treated as an LPCTSTR but when you are reading from the control you NEED A WRITEABLE STRINGUISH ITS Use for Input from Its Use for Output.

Therefore, you will offten find in My code Something That Looks Like

TVi.Item.psztext = (lpctstr) s;

This casts the CString to an LPCTSTR, thus giving me that address of the string, which I then force to be an LPTSTR so I can assign it. Note that this is valid only if you are using the value as data to a Set or Insert style method! you can not do this when you are trying to retrieve data! you need a slightly different method when you are trying to retrieve data, such as the value stored in a control. for example, for a CTreeCtrl using the GetItem method. Here I want to get the text of the item. I Know That the TEXT IN MORE THAN MY_LIMIT IN Size. Therefore, i can Write Something Like

TVItem TVi;

// ... Assotted Initialization of Other Fields of TVi

TVi.psztext = s.getBuffer (My_LIMIT);

TVi.cchtextmax = my_limit;

C_Mytree.GetItem (& TVI);

S.ReleaseBuffer ();

Note that the code above works for any type of Set method also, but is not needed because for a Set-type method (including Insert) you are not writing the string. But when you are writing the CString you need to make sure the buffer .................. ..

CString to BSTR

When programming with ActiveX, you will sometimes need a value represented as a type BSTR. A BSTR is a counted string, a wide-character (Unicode) string on Intel platforms and can contain embedded NUL characters.

You Can Convert At CString To A Bstr by Calling The CString Method Allocsystring:

CString S;

s = ...; //?

BSTR B = S.Allocsystring ();

The pointer b points to a newly-allocated BSTR object which is a copy of the CString, including the terminal NUL character. This may now be passed to whatever interface you are calling that requires a BSTR. Normally, a BSTR is disposed of by the Component receiving it. if you shop need to dispose of a bstr, you must use the call :: sysfreestring (b);

TO Free the string.

The story is that the decision of how to represent strings sent to ActiveX controls resulted in some serious turf wars within Microsoft. The Visual Basic people won, and the string type BSTR (acronym for "Basic String") was the result.

BSTR to CSTRING

Since a BSTR is a counted Unicode string, you can use standard conversions to make an 8-bit CString Actually, this is built-in;.. There are special constructors for converting ANSI strings to Unicode and vice-versa You can also get BSTRs AS Results in a Variant Type, Which is a type return by various com and automation calls.

For Example, IF you do, in an afflication,

BSTR B;

B = ...; //?

CString S (b == null? L ": b)

works just fine for a single-string BSTR, because there is a special constructor that takes an LPCWSTR (which is what a BSTR is) and converts it to an ANSI string. The special test is required because a BSTR could be NULL, and the constructors do not Play Well with NULL inputs (thanks to Brian Ross for pointing this out!) This also only works for a BSTR that contains only a single string terminated with a NUL;. you have to do more work to convert strings that contain Multiple Nul Characters. Note That Embedded Nul Characters Generally Don't Work Well In Cstrings and Generally Should Be Avoided.

Remember, According to the Rules of C / C , if you have an lpwstr it will match a parameter type of lpcwstr (It!). In Unicode Mode, this Is Just The Constructor

CSTRING :: CString (LPCTSTR);

As INDICATED ABOVE, INSI MODE THERE IS A Special Construction for

CSTRING :: CString (lpcwstr);

this calls an internal function to convert the Unicode string to an ANSI string. (In Unicode mode there is a special constructor that takes an LPCSTR, a pointer to an 8-bit ANSI string, and widens it to a Unicode string!). Again Note the limitation imposed by the need to test for a bstr value which is null.

There is an additional problem as pointed out above:.. BSTRs can contain embedded NUL characters; CString constructors can only handle single NUL characters in a string This means that CStrings will compute the wrong length for a string which contains embedded NUL bytes You need to Handle this yourself. if You Look at the constructors in strcore.cpp, you will see what all do an lstrlen or equivalent to compute the length.

Note that the conversion from Unicode to ANSI uses the :: WideCharToMultiByte conversion with specific arguments that you may not like. If you want a different conversion than the default, you have to write your own.

IF you are compiling as unicode, THEN IS A Simple Assignment:

CSTRING Convert (BSTR B)

{

IF (b == null)

Return CString (_T ("));

CString S (b); // in Unicode Mode

Return S;

}

If you are in ANSI mode, you need to convert the string in a more complex fashion. This will accomplish it. Note that this code uses the same argument values ​​to :: WideCharToMultiByte that the implicit constructor for CString uses, so you would use this TECHNIQUE ONLY YOTED TO CHANGE SESE PARAMETERS To Do The Conversion In Some Other Fashion, for Example, Specifying a Different Default Character, A Different Set of Flags, etc .cstring Convert (BSTR B)

{

CString S;

IF (b == null)

Return S; // EMPTY for NULL BSTR

#ifdef unicode

s = B;

#ELSE

LPSTR P = S.GetBuffer (Systringlen (B) 1);

:: Widechartomultibyte (CP_ACP, // Ansi Code Page

0, // no flags

B, // Source Widechar String

-1, // Assumen Nul-Terminated

p, // target buffer

Systringlen (b) 1, // Target Buffer LENGTH

Null, // use system default char

NULL); // Don't Care if DEFAULT USED

S.ReleaseBuffer ();

#ENDIF

Return S;

}

Note that I do not worry about what happens if the BSTR contains Unicode characters that do not map to the 8-bit character set, because I specify NULL as the last two parameters. This is the sort of thing you might want to change.

Variant to cstring

Actually, I'VE Never Done this; I don't work in Com / Ole / ActiveX WHERE this Is An Issue. But I Saw a Posting by Robert Quirk on The Microsoft.public.vc.mfc NewsGroup on now to do this, And It develop silly not to include it in this Essay, So Here it is, with a bit More explanation and elaboration. Any Errors Relative to what he wrote is.

A VARIANT is a generic parameter / return type in COM programming. You can write methods that return a type VARIANT, and which type the function returns may (and often does) depend on the input parameters to your method (for example, in Automation, Depending On Which Method You Call, Idispatch :: Invoke May Return (Via One of Its Parameters) A Variant Which Holds A Byte, A Word, An Float, A Double, A Date, A Bstr, And About Three Dozen Other Types (SeeE the specifications of the VARIANT structure in the MSDN). in the example below, it is assumed that the type is known to be a variant of type BSTR, which means that the value is found in the string referenced by bstrVal. This takes advantage of the fact that there is a constructor which, in an ANSI application, will convert a value referenced by an LPCWCHAR to a CString (see BSTR-to-CString). in Unicode mode, this turns out to be the normal CString constructor. See the Caveats About The Default :: Widechartomultibyte Conversion and WHether OR Not You Find these Acceptable (MOSTLY, You Will) .variant Vadata;

Vadata = m_com.Yourmethodhere ();

Assert (VADATA.VT == Vt_BSTR);

CString strdata (vadata.bstrval);

Note That You Could Also Make A More Generic Conversion Routine That Looted At The VT Field. In this case:

CString VariantToString (Variant * VA)

{

CString S;

Switch (VA-> VT)

{/ * vt * /

Case VT_BSTR:

Return Cstring (Vadata-> BStriguration);

Case vt_bstr | vt_byref:

Return CString (* vadata-> pbstrv);

Case vt_i4:

S.Format (_T ("% d"), VA-> LVAL);

Return S;

Case vt_i4 | VT_BYREF:

S.Format (_T ("% d"), * va-> plval);

Case vt_r8:

S.Format (_T ("% f"), VA-> DBLVAL);

Return S;

... Remaining Cases Left as an an EXERCISE for the ReaderDefault:

Assert (false); // unknown variant type (this assert isbotional)

Return CString ("");

} / * vt * /

}

Loading stringTable VALUES

If you want to create a program that is easily ported to other languages, you must not include native-language strings in your source code. (For these examples, I'll use English, since that is my native language (aber Ich kann ein Bischen deutsch sprechen). SO it is very bad practice to WRITE

CString s = "there is an error";

INSTEAD, You Should Put All Your Language-Specific Strings (Except, Perhaps, Debug Strings, Which Are Never in a product Deliverable). This means this is fine to write

S.Format (_T ("% D -% s"), code, text);

In Your Program; That Literal String is Not Language-Sensitive. However, You Must Be Very Careful To Not Use Strings Like

// fmt is "error in% s file% s"

// readorwrite is "Reading" or "Writing"

S.Format (FMT, ReadorWrite, FileName);

I speak of this from experience. In my first internationalized application I made this error, and in spite of the fact that I know German, and that German word order places the verb at the end of a sentence, I had done this. Our German distributor complained bitterly that he had to come up with truly weird error messages in German to get the format codes to do the right thing. It is much better (and what I do now) to have two strings, one for reading and one for writing And Load the appropriate ONE, MAKING THEM STRING Parameter-Insensitive, That IS, INSTEAD OF Loading The strings "r" ore "Writing", Load The Whole Format:

// fmt is "Error in Reading File% S"

// "Error In Writing File% S" S.Format (FMT, FileName);

Note That if you have more Than One Substitution, You Should Make Sure That If The Word ORDER of The Substitutions Does Not Matter, for Example, Subject-Object, Subject-Verb, or Verb-Object, in English.

For now, I will not talk about FormatMessage, which actually is better than sprintf / Format, but is poorly integrated into the CString class. It solves this by naming the parameters by their position in the parameter list and allows you to rearrange them in The output string.

So how do we accomplish all this? By storing the string values ​​in the resource known as the STRINGTABLE in the resource segment. To do this, you must first create the string, using the Visual Studio resource editor. A string is given a string ID Typically starting IDS_. so you have a message, you create the string and call it ids_reading_file and another called ids_writing_file. They Appear in Your.rc File AS

StringTable

IDS_Reading_File "Reading File% S"

IDS_Writing_File "Writing File% S"

End

Note: these resources are always stored as Unicode strings, no matter what your program is compiled as They are even Unicode strings on Win9x platforms, which otherwise have no real grasp of Unicode Then you go to. (But they do for resources!). Where you have had stiled the strings

// previous code

CSTRING FMT;

IF (...)

FMT = "Reading File% S";

Else

FMT = "Writing File% S";

...

//MUCH LATER

CString S;

S.FORMAT (FMT, FileName);

And instead do

// Revised Code

CSTRING FMT;

IF (...)

FMT.LOADSTRING (IDS_READING_FILE);

Else

FMT.LOADSTRING (DS_WRITING_FILE);

...

//MUCH LATER

CString S;

S.FORMAT (FMT, FileName);

Now your code can be moved to any language. The LoadString method takes a string ID and retrieves the STRINGTABLE value it represents, and assigns that value to the CString.There is a clever feature of the CString constructor that simplifies the use of STRINGTABLE entries. It is not explicitly documented in the CString :: CString specification, but is obscurely shown in the example usage of the constructor! (Why this could not be part of the formal documentation and has to be shown in an example escapes me!). The feature is that if you cast a STRINGTABLE ID to an LPCTSTR it will implicitly do a LoadString Thus the following two examples of creating a string value produce the same effect, and the ASSERT will not trigger in debug mode compilations.:

CString S;

s.LoadString (IDS_WHATEVER);

CString T ((LPCTSTR) IDS_WHATEVER);

Assert (s == T);

Now, You May Say, How Can This Possibly Work? How Can IT Tell A Valid Pointer from A StringTable ID? Simple: All String IDs Are In The Range 1..65535. This Means That The High-Order Bits of The Pointer Will BE What I HAVALID DATA in A LOWIER IS, You Can't. The Lower 64k of Your Address Space Will Never, Ever, Exist. any Attempt to Access a value in the address range 0x00000000 through 0x0000FFFF (0..65535) will always and forever give an access fault. These addresses are never, ever valid addresses. Thus a value in that range (other than 0) must necessarily represent a STRINGTABLE ID.

I tend to use the MAKEINTRESOURCE macro to do the casting. I think it makes the code clearer regarding what is going on. It is a standard macro which does not have much applicability otherwise in MFC. You may have noted that many methods take either a UINT or an LPCTSTR as parameters, using C overloading. This gets us around the ugliness of pure C where the "overloaded" methods (which are not really overloaded in C) required explicit casts. This is also useful in assigning resource names to Various Other Structures.cstring S;

s.LoadString (IDS_WHATEVER);

CString T (MakeintResource (IDS_WHATEVER));

Assert (s == T);

Just to give you an idea: I practice what I preach here You will rarely if ever find a literal string in my program, other than the occasional debug output messages, and, of course, any language-independent string..

CStrings and Temporary Objects

Here's a little problem that came up on the microsoft.public.vc.mfc newsgroup a while ago I'll simplify it a bit The basic problem was the programmer wanted to write a string to the Registry So he wrote...:

I am Trying to set a registry value using regsetvalueex () and it is the value there is ing i declare a variable of char [] IT Works Fine. However, I am Trying to convelectr from a cstring and i get Garbage. "ýý ... ýýýýý" to Be Exact. I have tried to char *, lpcstr. The return of getBuffer (from debug) is The Correct string Buthen i assign it to a char * (or LPCSTR) IT IS Garbage. FOLLOWING IS A PIECE OF MY CODE:

Char * szname = getName (). getBuffer (20); RegSetValueex (HKEY, "Name", 0. REG_SZ, (const Byte *) szname, Strlen (SZNAME 1)); The name string is less 20 Chars Long, SO i don't think to blame.it is very frust.dear frustrate,

You Have Been Done in by a fairly subtle error, caused by trying to be a bit to clever. What happened Was That You Fell Victim to knowing Too Much. The Correct Code Is Shown Below:

CString name = getName (); RegSetValueex (HKEY, _T ("name"), 0, reg_sz, (const byte *) (lpctstr) Name, (Name.getLength () 1) * sizeof (tchar));

Here's why my code works and yours didn't. When Your Function GetName Returned A CSTRING, IT RETURNED A "Temporary Object". See The C Reference Manual §12.2.

In some circumstances it may be necessary or convenient for the compiler to generate a temporary object. Such introduction of temporaries is implementation dependent. When a compiler introduces a temporary object of a class that has a constructor it must ensure that a construct is called for the Temporal Object. Similarly, The Destructor Must Be Called for a Temporary Object of a class where a destructor is declared.

The compiler must ensure that a temporary object is destroyed. The exact point of destruction is implementation dependent .... This destruction must take place before exit from the scope in which the temporary is created.

Most compilers implement the implicit destructor for a temporary at the next program sequencing point following its creation, that is, for all practical purposes, the next semicolon. Hence the CString existed when the GetBuffer call was made, but was destroyed following the semicolon. ( As an aside, there was no reason to provide an argument to GetBuffer, and the code as written is When the destructor was incorrect since there is no ReleaseBuffer performed). So what GetBuffer returned was a pointer to storage for the text of the CString. called at the semicolon, the basic CString object was freed, along with the storage that had been allocated to it. The MFC debug storage allocator then rewrites this freed storage with 0xDD, which is the symbol "Ý". By the time you do the write to the Registry, the string contents have been destroyed.There is no particular reason to need to cast the result to a char * immediately. Storing it as a CString means that a copy of the result is made, so after ....................

In Addition, My Code Is Unicode-Ready. The Registry Call Wants A Byte Count. Note Also That The Call Lstrlen (Name 1) Returns a Value That Is Too Small by 2 for an ANSI String, Since It Doesn't Start Until THE Second Character of the String. What You Meant To Write Was Lstrlen (Name) 1 (OK, I Admit It, I've Made The Same Error!). HOWEVER, IN Unicode, Where All Characters Are Two Bytes Long, WE need to cope with this The Microsoft documentation is surprisingly silent on this point:.? is the value given for REG_SZ values ​​a byte count or a character count I'm assuming that their specification of "byte count" means exactly that, and you have To Compensate.cstring Efficiency

ONE PROBLEM of CSTRING IS That It Hides Certain inefficiencies from you. On The Other Hand, IT Also Means That It Can Implement Certain Efficiencies. You May Be Tempted to Say of The Following Code

CString s = somcstring1;

S = somcstring2;

S = somcstring3;

S = ","

S = somcstring4;

That it is horribly inefficient company company

Char s [1024];

LSTRCPY (S, SomeString1);

LSTRCAT (S, SomeString2);

LSTRCAT (S, SomeString 3);

LSTRCAT (S, ",");

LSTRCAT (S, SomeString4);

After all, you might think, first it allocates a buffer to hold SomeCString1, then copies SomeCString1 to it, then detects it is doing a concatenate, allocates a new buffer large enough to hold the current string plus SomeCString2, copies the contents to the buffer and concatenates the SomeCString2 to it, then discards the first buffer and replaces the pointer with a pointer to the new buffer, then repeats this for each of the strings, being horribly inefficient with all those copies.

The truth is, it probably never copies the source strings (the left side of the =) for most cases.In VC 6.0, in Release mode, all CString buffers are allocated in predefined quanta. These are defined as 64, 128, 256 , and 512 bytes. This means that unless the strings are very long, the creation of the concatenated string is an optimized version of a strcat operation (since it knows the location of the end of the string it does not have to search for it , as strcat would;. it just does a memcpy to the correct place) plus a recomputation of the length of the string So it is about as efficient as the clumsier pure-C code, and one whole lot easier to write and maintain.. And understand.

Those of you who are not sure this is what is really happening, look in the source code for CString, strcore.cpp, in the mfc / src subdirectory of your vc98 installation. Look for the method ConcatInPlace which is called from all the = Operators.

AHA! SO CSTRING ISN't Really "Efficient!" For example, if i create

CSTRING CAT ("MEW!");

.................................................. ..

IF this is how you think, be prepared to reeducate yourself. Somewhere in Your Career Somebody Taught You That You Always Had To Use As Little Space As Possible, And this Was a good string.

It is INCORRECT. IT IGNORES SOME SERIOSLY IMPORTANT ASPECTS OF REALITY.

If you are used to programming embedded applications with 16K EPROMs, you have a particular mindset for doing such allocation. For that application domain, this is healthy. But for writing Windows applications on 500MHz, 256MB machines, it actually works against you, and creates programs that perform far worse than what you would think of as "less efficient" code.For example, size of strings is thought to be a first-order effect. It is Good to make this small, and Bad to make it large. Nonsense . The effect of precise allocation is that after a few hours of the program running, the heap is cluttered up with little tiny pieces of storage which are useless for anything, but they increase the storage footprint of your application, increase paging traffic, can actually slow down the storage allocator to unacceptable performance levels, and eventually allow your application to grow to consume all of available memory. Storage fragmentation, a second-order or third-order effect, actually domin ATES System Performance. Eventually, IT Completely Unacceptable.

Note this.

Assume your application is going to run for months at a time. For example, I bring up VC , Word, PowerPoint, FrontPage, Outlook Express, Forté Agent, Internet Explorer, and a few other applications, and essentially never close them. I ' ve edited using PowerPoint for days on end (on the other hand, if you've had the misfortune to have to use something like Adobe FrameMaker, you begin to appreciate reliability; I've rarely been able to use this application without it crashing four to six times a day! and always because it has run out of space, usually by filling up my entire massive swap space!) Precise allocation is one of the misfeatures that will compromise reliability and lead to application crashes.By making CStrings be multiples of some quantum, the memory allocator will end up cluttered with chunks of memory which are almost always immediately reusable for another CString, so the fragmentation is minimized, allocator performance is enhanced, application footprint remains almost a SMALL As Possible, And You Can Run for Weeks or Months without Problem.

Aside: Many years ago, at CMU, we were writing an interactive system Some studies of the storage allocator showed that it had a tendency to fragment memory badly Jim Mitchell, now at Sun Microsystems, created a storage allocator that maintained running statistics about.. allocation size, such as the mean and standard deviation of all allocations. If a chunk of storage would be split into a size that was smaller than the mean minus one s than the prevailing allocation, he did not split it at all, thus avoiding cluttering up the allocator with pieces too small to be usable. He actually used floating point inside an allocator! His observation was that the long-term saving in instructions by not having to ignore unusable small storage chunks far and away exceeded the additional cost of doing A Few Floating Point Operations ON AN Allocation Operation. He Was Right.Never, EVER Think About "Optimization" in Terms of Small-Fast Analyzed ON A Per-Line-of-Code Basis. Optimization Should Mean small-and-fast analyzed at the complete application level (if you like New Age buzzwords, think of this as the holistic approach to program optimization, a whole lot better than the per-line basis we teach new programmers). At the complete application Level, Minimum-Chunk String Allocation is about the Worst Method You Could Possibly.

If you think optimization is something you do at the code-line level, think again Optimization at this level rarely matters Read my essay on Optimization:.. Your Worst Enemy for some thought-provoking ideas on this topic.

Note That The = Operator is Special-Cased; if you want to write:

CString s = SomeCString1 SomeCString2 SomeCString3 "," SomeCString4; then each application of the operator causes a new string to be created and a copy to be done (although it is an optimized version, since the length of the string is KNown and the inefficiencies of strat do not come into play.

Summary

These are just some of the techniques for using CString. I use these every day in my programming. CString is not a terribly difficult class to deal with, but generally the MFC materials do not make all of this apparent, leaving you to figure it out ON your OWN.

Acknowledgements

Specting Out A Syntax Error In One of the Examples, Brian Ross For His Comments on BSTR Conversions, And Robert Quirk for His Example of Variant-To-BStr Conversion.

转载请注明原文地址:https://www.9cbs.com/read-3037.html

New Post(0)