1

The only question i found that tried to help me was this one C++: splitting a string into an array. I'm new to c++ and i need to have an array of string that cointain each of these words that i have in this char.

Here is the code:

s3eFile* file = s3eFileOpen("chatTest/restrict_words.txt","rb"); 
        int len = s3eFileGetSize(file);

        char* temp = new char[len];
        if (file!=NULL)
        {
            s3eFileRead(temp,len,1, file);
            s3eFileClose(file);
        }

So i need to make this temp to turn in to an array so i can work with it? There's a way?

Community
  • 1
  • 1
user3120770
  • 199
  • 1
  • 7
  • 19

2 Answers2

3

maybe something like:

ifstream f("chatTest/restrict_words.txt");

vector<string> vec;

while (!f.fail())
{
  string word;
  f >> word; 
  vec.push_back(move(word));
}
ebasconp
  • 1,608
  • 2
  • 17
  • 27
  • Wow `move()`. Is that really important enough to be introduced at this level? I wish it were already automatic for `.push_back()`... –  Mar 28 '14 at 20:19
2

If this is a c++ code then i would recommend moving to std::string instead of char* and use powerful std tools like fstream, stringstream etc . The link which you have specified gives detailed answer on how to do it

    #include <string>
    #include <sstream>
    using namespace std;
    .
    .
    .
    s3eFile* file = s3eFileOpen("chatTest/restrict_words.txt","rb"); 
    int len = s3eFileGetSize(file);

    char* temp = new char[len];
    if (file!=NULL)
    {
        s3eFileRead(temp,len,1, file);

        //Adding Code here
        string str(temp);
        stringstream sstr(str)
        vector<string> str_array;
        string extracted;
        while(sstr.good()){
         sstr>>extracted;
         str_array.push_back(extracted);
        }
        //at this point all the strings are in the array str_array

        s3eFileClose(file);
    }

you can access the strings using iterator or by simple indexing like arrays str_array[i]

Ravi
  • 255
  • 3
  • 16
  • How do i clean that char* temp after i use it? – user3120770 Mar 27 '14 at 16:57
  • i can do the same thing with the s3eFile* file right? – user3120770 Mar 27 '14 at 17:02
  • Well, I don't know about s3eFileOpen and s3eFileClose function. One would have to look at its documentation/implementation to know for sure whether to free/delete the memory or not. – Ravi Mar 27 '14 at 17:06
  • @Ravi If open allocates, I'd expect close to delete. But you definitely never know with 3rdparty offshoots. –  Mar 28 '14 at 20:05