Manipulating a char array

What is a simple method to insert a character into a char?

[Code]

Char name[] = "last";

Strcat(name,"first")

But instead insert first in front of last?


[/code]
If we're using C++, we should probably use strings rather than raw arrays of char and C library functions.

1
2
3
4
5
6
7
8
9
#include <iostream>
#include <string>

int main() {
    std::string name = "last";
    name = "first, " + name;

    std::cout << name << '\n' ;
}


But if you're stuck using raw arrays of char and C library functions the "simple" way would be to copy or move the "last" bit of the string to where you want it in the array, then copy the "first" bit where you want that. Unfortunately there is no library function that will do that for you with a single call.


Okay, this isn't pretty, but it accomplishes taking input and formatting a 10 digit number:

#include "stdafx.h"
#include <iostream>


using namespace std;
const int MAXLEN = 50;

int main()
{

char format[MAXLEN] = "(";
char unfnumber[MAXLEN];
cout << "Please enter a number to format:" << endl;
cin >> unfnumber;

char areacode[MAXLEN]; char prefix[MAXLEN]; char suffix[MAXLEN];

for (int i = 0; i<3;i++)
{
areacode[i] = unfnumber[i];
areacode[3] = 0;

}
for (int i = 0; i < 3; i++)
{
prefix[i] = unfnumber[i + 3];
prefix[3] = 0;
}

for (int i = 0; i < 4; i++)
{
suffix[i] = unfnumber[i + 6];
suffix[4] = 0;
}



strcat_s(format, MAXLEN, areacode);
strcat_s(format, MAXLEN, ") ");
strcat_s(format, MAXLEN, prefix);
strcat_s(format, MAXLEN, "-");
strcat_s(format, MAXLEN, suffix);


cout << format << endl;

return 0;
}

My exercise is suppose to help better familiarize me with char character in C++.
Topic archived. No new replies allowed.