Read Word From File Then Append to *char[] Does Not Do as Expected--Help!

*message.txt
 
Tree for me

*I'm able to read each word from a file with
 
char word[10];

*Then I'm trying to put each word into
 
char *words[3];

*Problem is each value in words has the memory address of word, thus every value in words becomes the last value that word was changed to. For example, the output at the end of words at the end of the program would be
 
words = {me, me, me}

*What I want is this...
 
words = {Tree, for, me}

*This is the code I wrote to append text from file to word into words
1
2
3
4
5
6
7
8
9
10
11
12
13
int main(){
   ifstream inFile;
   int size = 9;
   char *words[size];
   char word[10];

   inFile.open("message.txt");

   while(inFile >> word){
      static int count = 0;
      words[count++] = word;
   }
}


Please show me how to correct it!

NOTE:
*Please do not provide me with solutions utilizing the string, vector, or any other classes like them.
Last edited on
Have you considered using a vector of string?

If you must stick with the C-string and an array then you either need to use a statically allocated array (array[10][100]) or allocate memory for that pointer with new.

Also you can't use the assignment operator with C-strings, you'll need to either use the extraction operator to extract the "words" into your strings or use functions from the <cstring> header to copy the strings from your temporary variable to the destination variable.

Lastly you should never use a function to retrieve a C-string that doesn't limit the number of characters it will try to retrieve, to avoid buffer overrun problems.

Something like the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <fstream>
#include <iomanip>

const int MAX_WORD_SIZE = 50;
const int MAX_NUM_WORDS = 100;

int main()
{
    std::ifstream inFile("message.txt");
    // In C++ array sizes must be compile time constants!
    char words[MAX_NUM_WORDS][MAX_WORD_SIZE];

    int count = 0;
    // The setw() function will limit the number of characters the extraction operator will try to retrieve.
    while(count < MAX_NUM_WORDS && inFile >> std::setw(MAX_WORD_SIZE) >> words[count])
    {
        count++;
    }
    
    return 0;
}




char * words[3];
words[0] = new char[100];
words[1] = new char[100];
words[2] = new char[100];

strcpy(words[0], "tree");
strcpy(words[1], "for";
strcpy(words[2], "me");

I think that is what you are trying to do?

jlb has got it!
Topic archived. No new replies allowed.