2012-10-21 65 views
0

你有任何想法如何從流中填充單詞的數組?這是據我能去現在:如何用單詞填充二維字符數組?

ifstream db; 
db.open("db") //1stline: one|two|three, 2d line: four|five|six.... 
int n=0,m=0; 
char a[3][20]; 
char c[20]; 
while(db.get(ch)) { 
    if(ch=='|') { 
     a[0][m]=*c; 
     m++; 
    } 
    else { 
     c[n]=ch; 
     n++; 
    } 
} 

,使它看起來像{{一,二,三},{四,五,六} {七,八,九}, ...}

+1

請改善您的代碼。什麼是數據庫?什麼是其他一切? –

+0

done ............ –

回答

0

要保存「單詞」(字符串)的二維數組,需要三維字符數組,因爲字符串是一維字符數組。

您的代碼應的東西如下所示:

int i = 0; // current position in the 2-dimensional matrix 
      // (if it were transformed into a 1-dimensional matrix) 
int o = 0; // character position in the string 

int nMax = 20; // rows of your matrix 
int mMax = 3; // columns of your matrix 
int oMax = 20; // maximum string length 

char a[nMax][mMax][oMax] = {0}; // Matrix holding strings, zero fill to initialize 

char delimiter = '|'; 

while (db.get(ch)) { // Assumes this line fills ch with the next character from the stream 
    if (ch == delimiter) { 
     i++; // increment matrix element 
     o = 0; // restart the string position 
    } 
    else { 
     o++; // increment string position 
     a[i/mMax][i % mMax][o] = ch; 
    } 
} 

對於輸入流"one|two|three|four|five|six|seven"這將返回一個字符串,它看起來像一個數組:

{{"one", "two", "three"}, {"four", "five", "six"}, {"seven"}}

+1

要支持輸入格式(第一行:one | two | three,2d line:four | five | six ...),您可能還需要添加'char delimiter2 ='\ n'' – anatolyg

0

您可以使用C++對象如vectorstring。 C中的二維數組對應於C++中的向量向量。二維數組中的項目是字符串,因此下面的語法爲vector<vector<string>>

#include <vector> 
#include <string> 
#include <sstream> 
using std::vector; 
using std::string; 
using std::istringstream; 
vector<vector<string> > a; 
string line; 
while (getline(db, line, '\n')) 
{ 
    istringstream parser(line); 
    vector<string> list; 
    string item; 
    while (getline(parser, item, '|')) 
     list.push_back(item); 
    a.push_back(list); 
} 

此代碼(未測試;對於可能的語法錯誤抱歉)使用「字符串流」來解析輸入線;它不假定每行有3個項目。修改以適應您的確切需求。