need help with return char array

Hi guys,

I'm currently learning pointer with array but i'm stuck at some point. Can someone guide me along which part of the code did I miss or did wrongly.

This is my code.


#include <iostream>

using namespace std;

void printPattern(char* message)
{
int length = strlen(message);
for(int i=0;i<=length;i++) {

*message=i;
message+=1;
cout<<message<<endl;
}
}

int main(int argc, char* argv[]) {
char string1[] = "Application of C++";
printPattern(string1);

system("pause");
return 0;

}


It is actually working but not how I wanted it to be. Right now it is reducing each letter after a loop and at the ending, it show up with some weird characters. What I would want is it start off with 1 letter as the 1st line, follow by 2 letter at the 2nd line, and so on until it finishes the char[] which I had define in the main.

As for the weird character that shows up, from my understanding is that it is due to the NULL character therefore I would like to terminate the char array when it encounters the NULL.

I appreciate if someone can guide me on this =D
closed account (o3hC5Di1)
Hi there,

Your weird character most likely comes from this:

for(int i=0;i<=length;i++)

length is the amount of characters in the string. Arrays however are zero indexed, which means thatthey start counting at 0. So the first element of the array is array[0]. So you only need to loop until length-1:

for(int i=0;i<length;i++)


As for accessing the character you can just do this:

1
2
for(int i=0;i<length;i++) 
    cout<<message[i]<<endl;


Hope that helps.

All the best,
NwN
Hi NwN!

Thank you so much for your tips. After taking away the = sign at the for loop, the weird character is indeed gone. =D

However for the next part which you gave which is the message[I], by doing this it only print 1 letter on each line. what I would like is something like this.

A
Ap
App
Appl
Appli
.............


Do you have any idea how can I code this to get this kind of result?
Once again thank you so much for the help!
closed account (o3hC5Di1)
Hi there,

My apologies, I misunderstood, I thought you wanted each letter of the word on a new line.
You will need to use a nested for loop. The first for loop takes care of the lines, the next of the characters:

1
2
3
4
5
6
7
for (int i=0; i<length; ++i) //for every character, write a line
{
    for (int j=0; j<=i; ++j) //for every character up to the one which "line" we're on
        std::cout << array[j];

    std::cout << std::endl; //start new line
}


Hope that makes sense.

All the best,
NwN
Hi NwN,

Arr~! yes I was thinking whether is it a nested for loop that I miss out. hee. thanks a lot I will try it out =D
yea! it works! thanks so much for the help NwN ^^
closed account (o3hC5Di1)
Most welcome, glad it works :)

NwN
Topic archived. No new replies allowed.