将数据文件复制到数组中

Copying data file into an array

本文关键字:数组 复制 数据 文件      更新时间:2023-10-16

我有一个学校项目。他们给了我一个数据文件,需要在一个 10*10 的数组中。此数组需要是一个上三角形,这意味着对角线和对角线以下的所有值都必须为零。此数据文件是项目每个阶段所花费的时间。这意味着每个 [i][j] 表示从 i 到 j 的阶段时间。只是为了使问题更加复杂,要求您找到每列的最长时间,并将其添加到下一列中的最长时间。这是我到目前为止的代码:

#include <iostream>
#include<iomanip>
#include <fstream>
#include <cmath>
using namespace std;
//Function prototype
int minCompletionTime (int Data[], int numTasks);
int main()
{
    //Declaring and initializing variables
    int num_Events(0), completion_Time(0);
    int startSearch(0), endSearch(0);
    const int SIZE(10);
    char datch;
    //Declaring an array to hold the duration of each composite activity
    int rows(0),duration_Data [10];
    //Declaring an input filestream and attaching it to the data file
    ifstream dataFile;
    dataFile.open("duration.dat");
    //Reading the data file and inputting it to the array. Reads until eof
    //marker is read
    while (!dataFile.eof())
    {
        //Declaring an index variable for the array
        //Reading data into elements of the array
        dataFile >> duration_Data[rows];
        //Incrementing the index variable
        rows++;
    }
    //Taking input for the number of events in the project
    cout << "Enter the number of events in the project >>> ";
    cin  >> num_Events;
    //Calling the function to calculate the minimum completion time 
    completion_Time = minCompletionTime(duration_Data, num_Events);
    //Outputting the minimum completion time
    cout << "The minimum time to complete this project is " << completion_Time
        << "." << endl;
}
int minCompletionTime (int Data[], int numTasks)
{
    int sum=0;
    //As long as the index variable is less than the number of tasks to be
    //completed, the time to complete the task stored in each cell will be 
    //added to a sum variable
    for (int Idx=0; Idx < numTasks ; Idx++)
    {
        sum += Data[Idx];
    }
    return sum;
}

任何帮助将不胜感激 我的数据文件只有 6 个包含此元素的元素:9 8 0 0 7 5我的数据应如下所示,以便开始执行操作。

0 0 0 0 0 0 0 0 0 0 
0 0 9 8 0 0 0 0 0 0 
0 0 0 0 7 0 0 0 0 0
0 0 0 0 5 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0

这有点令人困惑。对不起。第一列和第二列的值应为零,第一行的值应相同。第五行之后也应该全为零,因为它将填充来自其他数据文件的更多信息。

有几种方法可以解决这个问题。这里有2种非常幼稚的方式:

1. 使用 10x10 数组:

  • 从数据文件(dataFile >> data[row][col])中读取所有内容。
  • 有 2 个嵌套循环:
    • 外部循环遍历列。
    • 内部循环循环访问该特定列的行。
    • 由于您必须找到最大值并且对角线下的值为零,因此您可以偷懒地找到每列的最大值(如果它大于 10x10,您可能会遇到麻烦)。但是,如果您只想浏览必要的行,我会让您弄清楚(这很简单,不要过度思考)。

2. 仅使用 1x10 数组:

  • 用最小值初始化数组(0 或 -1 应该适合你),我们称之为 max_row .
  • 逐行读取项目,并将其与存储在max_row中的值进行比较并相应地替换。
  • 完成后,只需总结max_row中的元素即可。