【发布时间】:2014-12-29 01:12:35
【问题描述】:
所以我的任务是从 .txt 文件中读取两个二维数组。该文件如下所示:
2 3 4 5 6 7
2 6 8 2 4 4
6 3 3 44 5 1
#
4 2 1 6 8 8
5 3 3 7 9 6
0 7 5 5 4 1
“#”字符用于定义两个数组之间的边界。
两个二维数组都必须动态分配。这就是我所拥有的:
int col = 0, row = 1;
int temp = 0;
char c;
ifstream file("input1.txt");
col = 0;
row = 1;
// calculating the no. of rows and columns of first 2d array in the text file (don't know how to do that for the second but this works perfectly)
do {
file.get(c);
if ((temp != 2) && (c == ' ' || c == '\n'))
col++;
if (c == '\n')
{
temp = 2;
row++;
}
} while (file);
// Used for rewinding file.
file.clear();
file.seekg(0, ios::beg);
// now I am using the info on rows and columns to dynamically allocate 2d array.(this is working fine too)
int** ptr = new int*[row];
for (int i = 0; i < col; i++)
{
ptr[i] = new int[col];
}
// here I am filling up the first 2d array.
for (int i = 0; i < row; i++)
{
for (int k = 0; k < col; k++)
{
file >> ptr[i][k];
cout << ptr[i][k] << ' ';
}
cout << endl;
}
// code above works fine when there is only one matrix in file(without the '#' sign)
// these are used for storing dimensions of second 2d array and for dynamically allocating him
int row_two = 1, col_two = 0;
现在,为了识别“#”字符并继续阅读下一个矩阵,我接下来应该做什么?下一个二维数组应该被称为ptr_two。
请注意,我不能使用向量,只能使用二维数组。
【问题讨论】:
-
什么是
fajl?此外,您应该找到一种无需两次读取文件的方法。考虑使用 'getline()' 和stringstream。 -
您可以使用动态存储容器,每次读取时添加一个字符。无需重读文件
-
请修改您的问题。
-
@DwayneTowell 'fajl' 是我的语言中的文件名称。现在修好了。我想到了这一点,如果我能找到一种只读取整个文件一次的方法,那就太好了,但我不知道该怎么做。而且我真的不知道怎么用
stringstream我还在c++的开始.. -
@dwn 我该怎么做?什么是储存容器?
标签: c++