C ++ 2d读入数组的麻烦

时间:2016-03-04 00:06:44

标签: c++ multidimensional-array

我需要帮助读取一个文本文件,该文件包含第一行和第一列的字符串整数。我需要以表格格式打印所有内容。我已经在一个只有浮点数的编辑文本文件中读取的程序,并且工作正常。该程序旨在读取文本文件,找到每行和每列的平均值和总数,并将其全部打印在表格中,但我不确定如何解决这个问题。该表应该像这样打印:

Department-Name Electric Copier Phone Miscellaneous sumOfRows totalOfRows
Bookkeeping 434.92 233.76 322.25 1442.98
Sales 610.55 233.21 144.75 1232.20
Service 343.21 224.76 128.90 987.00
Customer Relations 278.23 98.43 177.34 899.32
Marketing 522.32 109.78 233.45 1232.45
Media 132.98 221.43 119.56 1090.30
Human-Resources 109.56 342.87 298 1154
sumOfColumns
totalofColumns

我被告知我可以输入两个字符串数组,一个用于第一行,一个用于第一列,但我不确定如何以表格格式打印出来。

这是文件:

Department-Name Electric Copier Phone Miscellaneous 
    Bookkeeping 434.92 233.76 322.25 1442.98
    Sales 610.55 233.21 144.75 1232.20
    Service 343.21 224.76 128.90 987.00
    Customer Relations 278.23 98.43 177.34 899.32
    Marketing 522.32 109.78 233.45 1232.45
    Media 132.98 221.43 119.56 1090.30
    Human-Resources 109.56 342.87 298 1154

这是我的代码:

#include "stdafx.h"
#include <iostream>
#include  <fstream>
#include  <stdlib.h>

using namespace std;

const int ROWSPACE = 7;
const int COLUMNSPACE = 4;
float rowAverage[ROWSPACE] = {0}; 
float colAverage[COLUMNSPACE] = {0};
float rowTotal[ROWSPACE] = {0}; 
float colTotal[COLUMNSPACE] = {0};

float getAverage(float averageArray[][COLUMNSPACE], int size, float rowAverage[], float colAverage[]);
float calcTotal(float sumArray[][COLUMNSPACE], int sz, float rowTotal[], float colTotal[]);
void getData(float expense[][COLUMNSPACE], int ROWSPACE);
void printTable();

int _tmain(int argc, _TCHAR* argv[])
{
    printTable();//Prints the data.
    system("pause");
    return 0;
}

float getAverage(float averageArray[][COLUMNSPACE], int size, float rowAverage[], float colAverage[])//Finds the sums of the rows and columns.
{
    int i,j;
    float sum = 0, average;

    cout<<"These are the row averages: \n";
    for(i = 0; i<size; i++)
    {
        for(j=0; j<COLUMNSPACE; j++)
        {
            sum+=averageArray[i][j];//Finds the overall average
            rowAverage[i] += averageArray[i][j]; //Finds each row's average
            colAverage[j] += averageArray[i][j]; //Finds each column's average.
        }
        rowAverage[i] /= COLUMNSPACE; 
        cout<<rowAverage[i]<<"\t"; //prints the row averages
    }
    cout<<endl;
    cout<<"These are the column averages: \n";
    for(j=0; j<COLUMNSPACE; j++) 
    {
        colAverage[j] /= size; 
        cout<<colAverage[j]<<"\t"; //prints the column averages
    }

    average=sum/(size * COLUMNSPACE); 
    return average;
}

float calcTotal(float sumArray[][COLUMNSPACE], int sz, float rowTotal[], float colTotal[])
{
    int i,j;
    float sum = 0, total;

    cout<<"These are the row totals: \n";
    for(i = 0; i<sz; i++)
    {
        for(j=0; j<COLUMNSPACE; j++)
        {
            sum+=sumArray[i][j]; //Finds the overall total
            rowTotal[i] += sumArray[i][j]; //Finds the row totals
            colTotal[j] += sumArray[i][j]; //Finds the column totals
        }
        cout<<rowTotal[i]<<"\t"; //prints out row totals
    }
    cout<<"\nThese are the column totals: \n"; 
    for(j=0; j<COLUMNSPACE; j++) {
        cout<<colTotal[j]<<"\t"; //Prints out column totals
    }

    total=sum; 
    return total;
}

void getData(float expense[][COLUMNSPACE], int ROWSPACE)
{
    ifstream expenseFile;
    ofstream outFile;
    int i, j;

    expenseFile.open("Expense1.txt"); //reads in the file (I have Expense1 as the floats only, and Expense with the strings and the floats)
    outFile.open("newFile.txt"); //creates thew new file

    outFile<<"The expenses are: \n";

    for(i = 0; i<ROWSPACE; i++) //creates the array from the file
{
    for(j = 0; j<COLUMNSPACE; j++)
    {
        expenseFile>>expense[i][j];
        cout<<expense[i][j]<<"\t"; 
        outFile<<expense[i][j]<<"\t";
    }
    cout << endl;  //closes the expense file
    outFile << endl; //closes the new file
    }
}

void printTable() //prints out the data
{
    float average;
    float total;
    float expenseArray[ROWSPACE][COLUMNSPACE];
    cout<<"Electric Copier Phone Miscellaneous\n";
    getData(expenseArray,ROWSPACE);
    cout<<endl;
    average=getAverage(expenseArray,ROWSPACE,rowAverage, colAverage);
    cout<<endl;
    total= calcTotal(expenseArray, ROWSPACE, rowTotal, colTotal);
    cout<<endl;
}

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

使用结构数组,而不是2D数组。

一个原因是数组的所有元素必须具有相同的数据类型,因此如果不使用强制转换或union s来玩游戏,则无法混合字符串和浮点数。但是有了阶级或结构......你真的很开心!

struct datastruct 
{
    string DepartmentName; 
    float Electric; 
    float Copier; 
    float Phone; 
    float Miscellaneous;
};

如果允许,请选择std :: vector

std::vector<datastruct> list;

如果受奇数要求限制,则必须使用数组

datastruct list[ROWSPACE];

现在您可以逐行阅读该文件。以下内容改编自Read file line by line

std::string line;
std::getline(infile, line); // discard first line. It is only header information
while (std::getline(infile, line))
{
    std::istringstream iss(line);
    datastruct temp;
    if (!(iss >> temp.DepartmentName 
              >> temp.Electric
              >> temp.Copier
              ...)) 
    {
        // handle error 
    }

    // store temp in vector or array
    list.push_back(temp);
    // or
    list[index] = temp;
}

如果使用数组,则向while循环添加退出条件以防止超出数组末尾

当你很好地掌握C ++时,你也可以为结构重载>>并写一些更像

的内容
datastruct temp;
while (infile >> temp))
{
    // store temp in vector or array
}

但我不打算在这里介绍这个技巧。

传递它更容易,因为你现在有一维向量或数组。

float getAverage(vector<datastruct> & list, 
                 vector<float> &rowAverage, 
                 datastruct & colAverage)

float getAverage(datastruct list[], 
                 int size,  
                 float rowAverage[], 
                 datastruct & colAverage)

为了简化计算行和列的平均值,我们修改了数据结构

struct datastruct 
{
    string DepartmentName; 
    float Electric; 
    float Copier; 
    float Phone; 
    float Miscellaneous;

    float getAverage()
    {
        return (Electric + Copier + phone + Miscellaneous) / 4;
    }
    datastruct & operator+=(const datastruct & rhs)
    {
        Electric += rhs.Electric;
        Copier+= rhs.Copier;
        Phone+= rhs.Phone;
        Miscellaneous+= rhs.Miscellaneous;
        return *this;
    }
    datastruct & operator/=(float divisor)
    {
        Electric /= divisor;
        Copier/= divisor;
        Phone/= divisor;
        Miscellaneous/= divisor;
        return *this;
    }
};

并将其称为

for (auto & row: list)
{
    rowAverage.push_back(row.getAverage());
    colAverage += row;
}
colAverage /= size;

for(i = 0; i<size; i++)
{
    rowAverage[i] = list[i].getAverage();
    colAverage += list[i];
}
colAverage /= size;

此处,colAverge用于使用重载的+=运算符对列表中的所有项进行求和,然后用/=运算符除以大小。

请注意,colAverage在用于求和之前需要归零。您可能希望添加方法或构造函数来为您执行此操作。

计算总数是类似的。