1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
|
#include <iostream>
#include <cstring>
#include <cstddef>
using std::cout; using std::endl; using std::strcmp; using std::strlen; using std::strcat; using std::size_t;
int main()
{
// Declare 3 c_style strings from strings and compare them (note: the null character is automatically appended when a c_style string is initialized from a string).
const char css1[] = "A string.";
const char css2[] = "A different string.";
const char css3[] = "A string.";
// Comparing css1 to css2
if (strcmp(css1, css2) == 0)
cout << "css1 and css2 are equal!" << endl;
else
cout << "css1 and css2 are not equal!" << endl;
// Comparing css1 to css3.
if (strcmp(css1, css3) == 0)
cout << "css1 and css3 are equal!" << endl;
else
cout << "css1 and css3 are not equal!" << endl;
// Properly terminated c_style string.
const char ca[] = { 'h', 'e', 'l', 'l', 'o', '\0' };
const char *pChar = ca;
// Improperly terminated c_style string (null is not appended).
const char ca1[] = { 'h', 'e', 'l', 'l', 'o' };
const char *pChar1 = ca1;
// Loop through properly terminated ca.
while (*pChar) {
cout << *pChar << " ";
++pChar;
}
cout << endl;
// Loop through improperly terminated ca1.
while (*pChar1) {
cout << *pChar1 << " ";
++pChar1;
}
cout << endl;
// Create a character array with a size that will be able to hold css2 concatenated to css1 with a space in between the two strings plus room for the terminating null.
const size_t size = strlen(css1) + strlen(css2) + 2; // Includes room for a space between the strings and for the null character.
cout << "The concatenated string will have length " << size << endl;
char css4[30]; // Using magic number because won't compile with 'size' as dimension specifier. char css4[size] FAILS!
strcpy_s(css4, css1);
strcat_s(css4, " ");
strcat_s(css4, css2);
cout << css4 << endl;
return 0;
}
|