将数据文件复制到数组中

时间:2012-06-24 13:42:39

标签: c++ visual-studio-2010

我有一个上学项目。他们给了我一个数据文件,需要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

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

1 个答案:

答案 0 :(得分:0)

有几种方法可以解决这个问题。以下是两种非常天真的方式:

<强> 1。使用10x10阵列:

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

<强> 2。仅使用1x10阵列:

  • 使用最小值初始化数组(0或-1应该适合您),我们称之为max_row
  • 逐行阅读每一行,并将其与max_row中存储的值进行比较并进行适当替换。
  • 完成后,只需总结max_row中的元素。
相关问题