How do i fill two dimensional char array with words?

Do you have any idea how to populate array with words from stream? This is as far as i was able to go for now:

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

so that it looks like {{one,two,three},{four,five,six},{seven,eight,nine},...}

Upvotes: 0

Views: 3542

Answers (2)

anatolyg
anatolyg

Reputation: 28251

You can use c++ objects like vector and string. A two-dimensional array in C corresponds to a vector of vectors in c++. The items in the two-dimensional array are strings, hence the syntax vector<vector<string>> below.

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

This code (untested; sorry for possible syntax errors) uses a "string stream" to parse input lines; it doesn't assume 3 items per line. Modify to fit your exact needs.

Upvotes: 0

AffluentOwl
AffluentOwl

Reputation: 3647

To hold a 2-dimensional array of "words" (strings), a 3 dimensional array of characters is needed, since a string is a 1-dimensional array of characters.

Your code should something look like the following:

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

For the input stream "one|two|three|four|five|six|seven" this will return an array of strings which looks like:

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

Upvotes: 0

Related Questions