如何用单词填充二维char数组?

时间:2012-10-21 19:04:43

标签: c++

您是否知道如何使用流中的单词填充数组?这是我现在能够实现的目标:

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

所以它看起来像{{one,two,three},{four,five,six},{seven,eight,nine},...}

2 个答案:

答案 0 :(得分: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 :(得分:0)

您可以使用vectorstring等c ++对象。 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项。修改以满足您的确切需求。