C++ 读取任意大小的数组

C++ 读取任意大小的数组,c++,arrays,multiplication,C++,Arrays,Multiplication,以下代码在读取包含两个5X5数组的两个.txt文件时工作正常 #include <iostream> #include <string> #include <fstream> #include <sstream> #include <stdio.h> #include <vector> #include <sstream> using namesp

以下代码在读取包含两个5X5数组的两个.txt文件时工作正常

    #include <iostream>
    #include <string>
    #include <fstream>
    #include <sstream>
    #include <stdio.h>
    #include <vector>
    #include <sstream>

    using namespace std;

    int main()
    {
        string myFile, mysecondFile, mystring;
        string DIR;
        string extension;
        int total = 0;

        int number_of_lines = 0;
        string line;

        extension = ".txt";
        DIR = "H:\\Year2\\EE273\\EE273\\Week6\\";

        cout << "Enter the name of the file: \t";
        cin >> myFile;
        cout << "Enter the name of the second file: \t";
        cin >> mysecondFile;

        myFile = DIR + myFile + extension;
        mysecondFile = DIR + mysecondFile + extension;

        ifstream inFile;
        ifstream inFile2;

    int i=5;
    int j=5;
    int i2=5;
    int j2=5;
    int i3=5;
    int j3=5;
    int k;
    int l;

int Array[5][5];
int Array2[5][5];
int Array3[5][5];
string attempt1,attempt2;
int row = 0;
int col = 0;
int row2 = 0;
int col2 = 0;//i = row
                    //y = column

inFile.open(myFile.c_str());


if (!inFile) {
    cout <<"Error opening file"<<myFile<<endl;
    return -1;
}

while (!inFile.eof())
{
    getline(inFile, attempt1);
    stringstream iss( attempt1 );
    string result;
    col = 0;
    while (getline( iss, result, ','))
    {
        //cout << result << endl;
        Array[row][col] = atoi(result.c_str());
        //j = j + 1;
        col = col + 1;

    }
    row = row + 1;
}
inFile.close();

inFile2.open(mysecondFile.c_str());
if (!inFile2) {
    cout <<"Error opening file"<<mysecondFile<<endl;
    return -1;
}
while (!inFile2.eof())
{
    getline(inFile2, attempt2);
    stringstream iss( attempt2 );
    string result2;
    col2 = 0;
    while (getline( iss, result2, ','))
    {   
        //cout << result2 << endl;
        Array2[row2][col2] = atoi(result2.c_str());
        col2 = col2 + 1;
    }
    row2 = row2 + 1;
}
inFile2.close();

/*for (int i=0;i<5;i++){
    for (int j=0; j<5; j++){
        cout<<Array[i][j]<<endl;}}
for (int i2=0;i2<5;i2++){
    for (int j2=0; j2<5; j2++){
        cout<<Array2[i2][j2]<<endl;
    }}
#包括
#包括
#包括
#包括
#包括
#包括
#包括
使用名称空间std;
int main()
{
字符串myFile、mysecondFile、mystring;
字符串目录;
字符串扩展;
int-total=0;
int number_of_行=0;
弦线;
extension=“.txt”;
DIR=“H:\\Year2\\EE273\\EE273\\Week6\\”;
cout>myFile;
cout>mysecondFile;
myFile=DIR+myFile+扩展名;
mysecondFile=DIR+mysecondFile+extension;
河流充填;
IF2;
int i=5;
int j=5;
int i2=5;
int j2=5;
int i3=5;
int j3=5;
int k;
int l;
整数数组[5][5];
国际阵列2[5][5];
国际阵列3[5][5];
字符串attempt1,attempt2;
int行=0;
int col=0;
int row2=0;
int col2=0;//i=row
//y=列
open(myFile.c_str());
如果(!infle){

不能使用
std::vector
而不是原始数组。例如,你可以
push_back
向量上的一个项目。更重要的是,你可以创建一个只有在运行时才知道的大小,例如,从文件中的信息。最简单的方法要求文件包含矩阵的大小作为它的第一个条目。这样,你就可以放弃确认使用C(C++不允许动态大小的矩阵),并执行以下操作:

  • 将矩阵的维数读入变量
    宽度
    高度

  • 使用

    int (*dynamicMatrix)[width] = malloc(height*sizeof(*dynamicMatrix));
    
  • 重用代码以填充矩阵

  • 如果您不能退回到C,也不能使用
    std::vector
    ,那么您唯一需要做的就是使用双指针:

    int**dynamicMatrix = new int*[height];
    for(size_t i = width; i--; ) dynamicMatrix[i] = new int[width];
    
    同样,如果您可以定义文件中的前两个数字以包含文件中矩阵的宽度和高度,则这是最简单的。如果您无法将这两个数字编码到文件中,则必须在运行时增加动态数组:

    size_t lines = 0, allocatedLines = 8;
    int** dynamicMatrix = new int*[allocatedLines];
    while(/* can read a line */) {
        if(lines == allocatedLines) {
            int** temp = new int*[allocatedLines *= 2];
            for(size_t i = lines; i--; ) temp[i] = dynamicMatrix[i];
            delete[] dynamicMatrix;
            dynamicMatrix = temp;
        }
    
        //add one line
        size_t curLineLength = 0, allocatedLineLength = 8;
        dynamicMatrix[lines++] = new int[allocatedLineLength];
    
        //fill the line
        ...
    }
    
    用于重新分配一行的类似块需要进入循环,在循环中读取一行的元素。这很乏味;但要想做得更好,唯一的方法是使用不允许使用的东西


    顺便说一句:在C中,即使是重新分配内容也更容易,因为它提供了
    realloc()
    函数:

    size_t lines = 0, allocatedLines = 8;
    int** dynamicMatrix = malloc(allocatedLines * sizeof(*dynamicMatrix));
    while(/* can read a line */) {
        if(lines == allocatedLines) {
            //realloc takes care of copying the data to a new location (if that is necessary):
            allocatedLines *= 2;
            dynamicMatrix = realloc(dynamicMatrix, allocatedLines * sizeof(*dynamicMatrix));
        }
    
        //add one line
        size_t curLineLength = 0, allocatedLineLength = 8;
        dynamicMatrix[lines++] = malloc(allocatedLineLength * sizeof(**dynamicMatrix));
    
        //fill the line
        ...
    }
    
    因为没有等价的“代码> RealCube()/C++ >与<代码>新< /代码> /<代码>删除< /代码>,您需要在C++中使用<代码> STD::向量< /代码>,或者像上面那样复制自己。

    < P>“最简单”方法是做一些简单的事情,比如完全读取文件一次以获得行/列的数量,然后再次读取文件以实际将值存储在矩阵中:

    unsigned int rows = 0;
    unsigned int cols = 0;
    
    std::string line;
    while (std::getline(inFile, line)) {
        rows++;
        std::stringstream ss(line);
    
        std::string col;
        while (std::getline(ss, col, ',')) {
            cols++;
        }
    }
    
    // Now allocate the rows*cols matrix
    int** matrix = new int*[rows];
    for (int i = 0; i < rows; i++) {
        matrix[i] = new int[cols];
    }
    
    // and read your values into the matrix ...
    // matrix[m][n] = xxx
    
    现在,您可以读取文件的第一行,您将知道此文件的其余部分包含一个3x3矩阵。使用
    new
    分配矩阵(与上面的示例类似),然后继续将文件的其余部分读入其中

    记住使用
    delete[]
    清理动态分配的矩阵。每次调用
    new
    时,应该有一次调用
    delete

    for (int i = 0; i < rows; i++) {
        delete[] matrix[i];
    }
    delete[] matrix;
    
    for(int i=0;i
    使用而不是裸数组。问题是这是一个评估,他们告诉我们只使用arraysGee,你不认为你应该在你的帖子中包含这个约束吗?@Paolokiller:所以写一些行为类似于
    std::vector
    (当需要超出当前容量时重新分配和移动元素),然后使用它而不是裸数组。(是的,这将涉及
    new
    delete
    。您还应该了解。指针变戏法很棘手,这就是为什么我们有友好的库工具,如
    vector
    ,来为我们管理它。)@Paolokiller:你的意思是你不能用一个很好的类来管理数组?这是一个很奇怪的约束;但是如果真的是这样,就做同样的事情(分配一个更大的数组,移动数据,删除旧的数组)在一堆奇怪的未封装代码中。根据OP的评论,vector不能使用,因为这是一个赋值,他们被告知要使用数组。@Borgeader:是的,他在我发布了这个答案后发布了这个消息。我不打算追逐不断变化的需求。对这些信息做你想做的,我只是提供而已。这是一个愚蠢的要求我在C++中编写程序,所以我不认为我应该使用Maloc。我的想法是使用GETLIN读取TXT文件,并有一个变量行,一个列根据读取的文件增加。这有意义吗?我不知道如何做,但是我想如果我能得到PRO。GM来知道文件中有多少行/科尔,我可以得到其余的工作……我删除了提到的<代码> STD::vector 现在,用一个基本描述来代替它,在C++中没有它需要做什么。希望这有帮助。这正是我所要寻找的。只要GETLIN始终找到值,那么行和列W就可以找到。我会递增。我稍后会尝试代码,但我相信它会很好地工作。为什么你说它效率低下?如果我们想打开内容未知的.txt文件,这不是最有效的解决方案吗?@Paolokiller做任何事情两次总是比做同一件事花费更多的时间。特别是,从磁盘读取文件通常是一个缓慢的操作,因此您需要避免重复执行。在我的回答中,我包括了这样一种方法:
    在数据之前包括矩阵宽度/高度:)您还可以将文件存储为二进制文件,并使用
    seekg()
    tellg()确定大小
    ,但这也带来了其他复杂性(例如,不可读)。如果允许的话,[infile.txt] 3,3 1,2,3 4,5,6 7,8,9
    for (int i = 0; i < rows; i++) {
        delete[] matrix[i];
    }
    delete[] matrix;