CSC 076

Programming in C++

 

C++ String Swap Function

The following compares swap functions for C++ strings and C strings respectively

//File: swaps.cpp
#include <iostream>
#include <string>
using namespace std;

//C string swap
void cswap (char * p, char * q)
{
    char * temp = 0; //0 is the null pointer
    strcpy (temp, p);    //char * strcpy (char * s1, const char * s2);
    strcpy (p, q);        //copies the string s2 int s1.  The value of s1 is returned.
    strcpy (q, temp);
}

//C++ string swap
void cppswap (string & a, string & b)
{
    string temp = a;
    a = b;
    b = temp;
}

int main()
{
    char *     cstring1     = "First C String ";
    char *    cstring2      = "Second C String";
   
    string     string1         = "First C++ String ",
                string2         = "Second C++ String";
       
    cout     << "The C strings in order are:\t" << cstring1
                << "\t\t" << cstring2 << endl;
       
    cout    << "The C++ strings in order are: \t" << string1
                << "\t" << string2 << '\n' << endl;
       
    cout    << "AFTER THE SWAPS\n" << endl;
   
    cswap (cstring1, cstring2);
    cppswap (string1, string2);
   
    cout     << "The C strings in order are:\t" << cstring1
        << "\t\t" << cstring2 << endl;
       
    cout    << "The C++ strings in order are:\t" << string1
        << "\t" << string2 << endl;
       
    return 0;
}

The C strings in order are:       First C String           Second C String
The C++ strings in order are: First C++ String      Second C++ String

AFTER THE SWAPS

The C strings in order are:       Second C String           First C String
The C++ strings in order are: Second C++ String     First C++ String

Note that while the above program works fine using the DJGPP compiler, Visual C++ has fatal errors.  The following version of cswap() works just fine on either compiler:

//C string swap
void cswap (char * * p, char * * q)
{
    char * temp = *p; //0 is the null pointer
    *p = *q;
    *q = temp;
}

However, in main(), the calling reference must incorporate the "address", &, of the respective strings as follows:

    cswap (&cstring1, &cstring2);

The full program is found in swap2.cpp

Back to 2/26 Lecture