C++ char array Concatenate two char array strings

Description

C++ char array Concatenate two char array strings

#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;

void concatString(char szTarget[], const char szSource[]);

int main(int nNumberofArgs, char* pszArgs[])
{
    char charArray[256];
    cout << "Enter string #1:";
    cin.getline(charArray, 128);/*from w ww . j  av a  2s .com*/

    char szString2[128];
    cout << "Enter string #2:";
    cin.getline(szString2, 128);

    concatString(charArray, " - ");

    concatString(charArray, szString2);

    cout << "\n" << charArray << endl;

    return 0;
}

void concatString(char szTarget[], const char szSource[]){
    // find the end of the first string
    int targetIndex = 0;
    while(szTarget[targetIndex])
    {
        targetIndex++;
    }

    // tack the second onto the end of the first
    int sourceIndex = 0;
    while(szSource[sourceIndex])
    {
        szTarget[targetIndex] =
            szSource[sourceIndex];
        targetIndex++;
        sourceIndex++;
    }

    // tack on the terminating null
    szTarget[targetIndex] = '\0';
}



PreviousNext

Related