我如何用单词填充二维字符阵列
How do i fill two dimensional char array with words?
您是否知道如何用流中的单词填充数组?这是我现在能做的:
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"}}
您可以使用vector
和string
等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个项目。修改以满足您的确切需求。
相关文章:
- 移动二维数组中的字符
- C++ 传递二维字符数组
- 如何检查二维字符数组是否有空字
- 如何将二维数组类型字符(字符串)作为函数参数传递?
- 如何填充二维字符数组?C++
- 我如何用单词填充二维字符阵列
- 给出预定义的二维字符数组值
- 如何将二维字符类型数组逐行保存到 c 中的.txt文件中
- 二维字符数组C++
- 从C++文件中读取二维字符数组
- 将字符串复制到二维字符数组时出错
- 使用strncpy将字符串复制到二维字符数组中
- 比较 C++ 中的二维字符数组
- 给定一个二维字符矩阵,我们必须检查给定的单词是否存在于其中
- 正在将内存分配给二维字符数组,错误:从“void*”到“char**”的转换无效
- 在检查二维字符数组中的重叠时遇到麻烦
- 如何将字符变量存储为二维字符变量
- C/C++ 中的二维字符数组
- 将二维字符数组初始化为全空白时出现问题
- 对二维字符数组进行排序?C++