我如何用单词填充二维字符阵列

How do i fill two dimensional char array with words?

本文关键字:二维 字符 阵列 何用单 填充      更新时间:2023-10-16

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

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

使它看起来像{{{一个,两个,三},{四,五,六个},{七,八,九,nine},...}

保存"单词"(字符串)的二维数组,需要一个三维字符数组,因为字符串是字符的1维数组。

您的代码应该看起来如下:

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

您可以使用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个项目。修改以满足您的确切需求。