Visual C++ and MFC Programming 2nd Edition

(Martin Jones) #1

Chapter 9 Strings Visual C++ and MFC Fundamentals


CExerciseDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);

char Make[] = "Ford ";
int LengthMake = strlen(Make);
char Model[] = "Explorer";
int LengthModel = strlen(Model);

char *Car = strncat(Make, Model, 3);
int LengthCar = strlen(Car);

pDC->TextOut(10, 20, Make, LengthMake);
pDC->TextOut(10, 40, Model, LengthModel);
pDC->TextOut(10, 60, Car, LengthCar);
}

The string class provides its own mechanism to add two strings. It uses the addition
operator. To do this, simply add one string value or variable to another string value or
variable and assign the result to the target string variable. Here is an example:

void CExerciseView::OnDraw(CDC* pDC)
{
CExerciseDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);

string Make = "Ford ";
string Model = "Explorer";

string Car = Make + Model;
int LengthCar = Car.length();

int LengthMake = Make.length();
int LengthModel = Model.length();

pDC->TextOut(10, 10, Make.c_str(), LengthMake);
pDC->TextOut(10, 30, Model.c_str(), LengthModel);
pDC->TextOut(10, 50, Car.c_str(), LengthCar);
}

Alternatively, to add two strings, you can call the append() method. It comes in various
versions as follows:

basic_string& append(const E *s);
basic_string& append(const E *s, size_type n);
basic_string& append(const basic_string& str,
size_type pos, size_type n);
basic_string& append(const basic_string& str);
Free download pdf