Passing data from one array to another using C-Strings.

Edit: I was wondering how to make a pointer to an array and then using that pointer put information into the array. Apparently, this is how I am supposed to fill the char array, and I can't seem to figure out the syntax. Any help would be appreciated.


Thanks for all of the help for the below, I have figured out mostly how to do it. Just need help with the above.

For one of my classes I have been asked to create a program that takes user input and stores it into a char array (c-string) that has 500 elements. However, if the input is anything but 0 I am supposed to continuously ask for more input. I believe this assignment is trying to show how to use char pointers. Once I have all of the input I am supposed to take all of the information that the user has entered and reverse it by entry.

I.E. if the user entered
Hello
There
it would return
There
Hello

On to my question. How would I go about taking the input that the user enters and adding it onto the char array to the next "available" position. Hope I wrote my question correctly. Thanks for any help that is given.
Last edited on
closed account (o3hC5Di1)
Hi there,

The easiest way would be to keep a counter variable:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const int ARRAY_SIZE=500;
const int STRING_SIZE=250;

int counter=0;

char user_text[ARRAY_SIZE][STRING_SIZE];
char temp[STRING_SIZE];

while (std::strcmp(temp, "quit") != 0) //while the user hasn't entered quit
{
    std::cout << "Please enter some text: ";
    std::cin >> tmp;
    std::strcpy(user_text[counter] , tmp);  //edited as per Disch's comment below
    ++counter; //increment counter by 1
}


It's best to check whether the input is not larger than STRING_SIZE, to avoid memory problems. As this is for an assignment about c-strings, you should probably use them, but I wanted to mention that using std::string is a much easier and safer alternative.

Hope that helps, please do let us know if you have any further questions.

All the best,
NwN
Last edited on
user_text[counter] = tmp;

You cannot assign arrays in this fashion.

To copy a C string from one array to another, use strcpy:


 
strcpy( user_text[counter], tmp );
Topic archived. No new replies allowed.