minecraftplayer1234
minecraftplayer1234

Reputation: 2227

Adding spaces at the beginning of an array of chars

As in the title, I need to add user-specified number of spaces at the beginning of some word, using array of chars. I need to do it in a function which takes my array as a parameter and returns it. Here's my code:

#include <iostream>

using namespace std;

void writeDownCharArray(char t[], int sizee)
{
    for (int i=0;i<sizee;i++)
    {
        cout<<t[i];
    }
}

char * addSpaces(char t[], int ammountOfSpaces)
{
    int numberOfCharacters=0;
    for (int i=0; t[i]!=NULL; i++){numberOfCharacters++;} //checking the amount of characters in my array
    char t2[numberOfCharacters+10];
    for (int i=0; i<ammountOfSpaces; i++) {t2[i]=' ';} //adding the sapces
    for (int i=ilosc;i<numberOfCharacters+ammountOfSpaces;i++) {t2[i]=t[i-ammountOfSpaces];} //filling my new array with characters from the previous one
    return t2;
}

int main()
{
    int numberOfSpaces;
    char t[10];
    cout << "Text some word: ";
    cin.getline(t,10);
    cout<<"How many spaces?: ";cin>>numberOfSpaces;
    writeDownCharArray(addSpaces(t, numberOfSpaces), HERE);
    return 0;
}

And now: How do I print it to the screen? If I say cout<<addSpaces(t, numberOfSpaces); it actually prints something strange to the screen (not numbers, just strange characters). And if I say writeDownCharArray, then what should I put in "HERE" place?

Upvotes: 1

Views: 2382

Answers (1)

NathanOliver
NathanOliver

Reputation: 180415

The C++ way to solve this would be to use a std::string like

std::string add_spaces(const std::string & line, std::size_t number_of_spaces)
{
    std::string spaces(number_of_spaces, ' ');
    return spaces + line;
}

If you cannot use std::string then you are doing to have to deal with dynamic memory allocations and change

char t2[numberOfCharacters+10];

to

char * ts = new char[numberOfCharacters + ammountOfSpaces + 1];

We have to have this as Variable length arrays are not standard and trying to return a pointer to an array declared in a function will leave you with a dangling pointer and trying to use it is undefined behavior.

Since new[] was used in the function you will need to remember to call delete[] on the pointer that is returned after you are done with it. This is another benefit of using a std::string as it takes care of itself.

As far as writeDownCharArray is concerned you do not need a size parameter as cout can handle null terminated c-strings. You can simply have

void writeDownCharArray(char t[])
{
    cout<<t;
}

And then you main would look like

char * foo = addSpaces(t, numberOfSpaces);
writeDownCharArray(foo);
delete [] foo;

Upvotes: 6

Related Questions