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

{{one,two,three},{four,five,six},{seven,eight,nine},...}のように見えるように

4

2 に答える 2

0

「単語」(文字列) の 2 次元配列を保持するには、文字列が文字の 1 次元配列であるため、文字の 3 次元配列が必要です。

コードは次のようになります。

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

于 2012-10-21T19:32:33.467 に答える
0

vectorや などの C++ オブジェクトを使用できますstring。C の 2 次元配列は、c++ のベクトルのベクトルに対応します。2 次元配列の項目は文字列であるため、次の構文になり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);
}

このコード (テストされていません。構文エラーの可能性があります) は、「文字列ストリーム」を使用して入力行を解析します。1 行に 3 つの項目があるとは想定していません。正確なニーズに合わせて変更します。

于 2012-10-21T19:51:00.637 に答える