dorothy
dorothy

Reputation: 1243

C++ multidimension array storing strings

I wish to store for example 10 words into a multi-d array. This is my code.

char array[10][80]; //store 10 words, each 80 chars in length, get from file
int count = 0;
while ( ifs >> word ){ //while loop get from file input stream <ifstream>
  array[count++][0] = word;
}

when i compile, there's error. "invalid conversion from ‘char*’ to ‘char’ ". ifs return a char pointer. How can i succesffuly store into array?

Upvotes: 1

Views: 117

Answers (3)

Charles Welton
Charles Welton

Reputation: 861

As this is C++, I would use the STL containers to avoid some char* limitations. word would have type std::string, array would have type std::vector<std::string> and you would push_back instead of assigning. The code looks like this:

#include <string>
#include <vector>

std::string word;
std::vector<std::string> array;
while(ifs >> word) {
   array.push_back(word);
}

This is better than char* for a few reasons: you hide the dynamic allocation, you have words with real variable size(up to memory size), and you don't have any issues if you need more than 10 words.

Edit: as mentioned in the comments, if you have a compiler that supports C++11, you can use emplace_back and std::move instead, which will move the string instead of copying it (emplace_back alone will construct the string inplace.)

Upvotes: 3

hahaya
hahaya

Reputation: 106

word is char*(string), but array[count++][0] is store a char, you can change "array[count++][0] = word;" to "strcpy(array[count++], word);"

char array[10][80]; //store 10 words, each 80 chars in length, get from file
int count = 0;
while ( ifs >> word ){ //while loop get from file input stream <ifstream>
  strcpy(array[count++], word);
}

Upvotes: 0

Ashish Tomer
Ashish Tomer

Reputation: 55

You should define a pointer to array I think, that can access each value of array blocks one by one (or the way you want). You can also try dynamic allocation. Those are pointer things so then it'll be comparable easily.

Upvotes: 0

Related Questions