2014-03-27 41 views
0

我發現試圖幫助我的唯一問題是這一個C++: splitting a string into an array。 我是新來的c + +,我需要有一個字符串數組,共同擁有這些字,我有這個字。如何創建一個字符串數組,用於分隔由「」分隔的單詞的字符? C++

下面是代碼:

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); 
     } 

所以我需要讓這個溫度在轉向一個數組,所以我可以使用它? 有一種方法?

+1

由於你正在使用新的,爲什麼不使用矢量而不是普通的數組? – ebasconp

+0

vector ?我想它確定我只需要知道如何去做 – user3120770

+0

使用'std :: string :: find'或它的一個親戚。另見'std :: string :: substr'。 –

回答

2

如果這是一個C++代碼,那麼我建議移動到std :: string而不是char *並使用強大的std工具,如fstream,stringstream等。您已指定的鏈接提供了有關如何做到這一點

#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); 
    } 

您可以訪問使用迭代器的字符串或通過簡單的索引數組類似詳細的解答str_array[i]

+0

工作很好,真的很感謝你 – user3120770

+0

我怎麼在使用它之後清理char * temp? – user3120770

+0

delete [] temp; – Ravi

3

也許是這樣的:

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

vector<string> vec; 

while (!f.fail()) 
{ 
    string word; 
    f >> word; 
    vec.push_back(move(word)); 
} 
+0

哇'移動()'。這個級別真的很重要嗎?我希望它已經自動爲'.push_back()'... – 2014-03-28 20:19:06