2016-11-19 23 views
-4

我需要一點點幫助解決這一問題,打破字符數組成字

你如何打破字符數組這樣的「字符*文本」到基於特定的分隔符個別單詞,並將它們保存形式「char * text []」,不使用strtok函數或除「iostream」之外的任何庫。

在正常情況下,我會使用字符串而不是char數組和strtok函數,但在這種情況下,我根本不被允許。

感謝,

更新: 我已經包括了我試圖

#include <iostream> 
#include <fstream> 
//#define MAX_CHARS_PER_LINE = 512; 
//#define MAX_TOKENS_PER_LINE = 5; 
using namespace std; 
char stringToken(char* input_string); 
int main(int argc, char* argv[]) 
{ 
    char input_string[512]; 
    ifstream infile; 
    infile.open(argv[1]); 
    while(!infile.eof()) 
    { 
     infile.getline(input_string, 512); 
     cout << "Main line: " << input_string << endl; 
     stringToken(input_string); 
    } 
    infile.close(); 
    return 0; 
} 
char stringToken(char* input_string) 
{ 
    //char* word; 
    //cout << "String token function: " << input_string << endl; 
    /*while(input_string >> word) 
    { 
     cout << word << endl; 
    }*/ 

    char *tempone; 
    char *temptwo[5]; 

    int ii=0, 
     jj=0; 
    while(input_string[ii] != '\0' && jj<5) 
    { 
     if((int)input_string[ii]!= 32 && (int)input_string[ii]!= 9 && (int)input_string[ii] != 44) 
     { 
      tempone[ii]=input_string[ii]; 
      //cout << "\n\nindiv char" << input_string[ii] << "\t\t" << (int)input_string[ii] << "\n\n"; 
     } 
     else 
     { 
      temptwo[jj]=tempone; 
      jj++; 
      //testing 
      cout << temptwo << endl; 
     } 
     ii++; 

    } 



    return 0; 
} 
+0

如果沒有這樣做,在C++中獲取某些東西有點困難。換句話說,例如,使用'strtok'。 – nbro

+0

我知道這很難,但你可以做一個[搜索](http://stackoverflow.com/questions/236129/split-a-string-in-c)。或者展示你的嘗試。你來,只是說「做我的工作thx!」。 – Stargateur

+0

@Stargateur我明白你的批評,但我一直在尋找一段時間,幾乎我發現的一切都需要使用字符串或矢量庫。 –

回答

0

這裏僞碼

words split(line, delims) 
{ 
    nb_words = cound_words(line); 
    words = allocate_words(nb_words + 1); // words is a array of pointer 
    i = 0 
    j = 0 
    while true 
    { 
     while line[i] in delims // we transform every delims into a end string 
     { 
      line[i] = end_string 
      i++ 
     } 
     if line[i] not end_string 
     { 
      words[j] = line + i // we stock the address of line[i] 
      j++ 
      while line[i] not in delims and line[i] not end_string 
      { 
       i++ 
      } 
     } 
     else 
     { 
      words[j] = NULL // we end the array by NULL pointer 
      return words 
     } 
    } 
} 

count_word使用類似的循環。我讓你找到它。該算法的目的是將該行轉換爲多個單詞。所以,只要你使用文字,行就必須活着。

+0

謝謝!什麼是「nb_words」的類型? –

+0

@VictorL nb_words在這裏**計數**的字數。而不是用於分配數組。所以他的類型與[new operator]的參數相同(http://www.cplusplus.com/reference/new/operator%20new/)。 – Stargateur