LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   simple c++ question (pointers) (https://www.linuxquestions.org/questions/programming-9/simple-c-question-pointers-142768/)

true_atlantis 02-05-2004 06:04 PM

simple c++ question (pointers)
 
im trying to take each word untill end of file and put it in 1 element of a vector...

i know that char *words[1000] are pointers, so, when i want to read in the words, i need to somehow create a new space for each new word, right now it is just overriding the previous word and so the words vector points to the same word... here is a simple code example...

Code:

int wordSze =0;
char *words[1000];

int main(){
        char input[101];
        cin >> setw(100) >> input;
        while(!cin.eof()){
                words[wordSize]=text;
                wordSize++;
                cin >> setw(100)>>input;
        }
       
        for(int i=0; i<wordSize; i++)
                cout <<words[i]<<endl;
        return 0;
}


so, this is what the output would look like

>countwords
hello, how are you (ctrl-d)
you
you
you
you
>


jailbait 02-05-2004 06:34 PM

"i need to somehow create a new space for each new word,"

You pick up the new memory with the malloc function. You store the address of the memory provided by malloc into the array element.

___________________________________
Be prepared. Create a LifeBoat CD.
http://users.rcn.com/srstites/LifeBo...home.page.html

Steve Stites


All times are GMT -5. The time now is 07:50 AM.