首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++ 2d读入数组故障

C++ 2d读入数组故障
EN

Stack Overflow用户
提问于 2016-03-04 00:06:43
回答 1查看 45关注 0票数 0

我需要在第一行和第一列都有字符串整数的文本文件中读取帮助。我需要把所有的东西都打印出来。我在一个编辑过的文本文件中读取的程序只有浮点数,并且工作正常。这个程序的目的是读取文本文件,查找每一行和每列的平均值和总数,然后在一个表中全部打印出来,但我不知道该如何处理。这张桌子应该是这样打印的:

代码语言:javascript
复制
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

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

以下是文件:

代码语言:javascript
复制
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

这是我的代码:

代码语言:javascript
复制
#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;
}

有什么建议吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-03-04 01:51:05

使用结构数组,而不是二维数组。

一个原因是数组的所有元素都必须具有相同的数据类型,所以如果不使用强制转换或union,就不能混合字符串和浮点数。你真的可以玩得开心!

代码语言:javascript
复制
struct datastruct 
{
    string DepartmentName; 
    float Electric; 
    float Copier; 
    float Phone; 
    float Miscellaneous;
};

如果允许的话,更倾向于std::载体

代码语言:javascript
复制
std::vector<datastruct> list;

如果受奇数要求绑定,则必须使用数组。

代码语言:javascript
复制
datastruct list[ROWSPACE];

现在您可以逐行读取该文件。以下内容来自于Read file line by line

代码语言:javascript
复制
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++之后,您还可以为该结构重载>>,并编写类似的内容

代码语言:javascript
复制
datastruct temp;
while (infile >> temp))
{
    // store temp in vector or array
}

但我不打算在这里掩盖这个诡计。

传递它要容易得多,因为您现在有一个一维向量或数组。

代码语言:javascript
复制
float getAverage(vector<datastruct> & list, 
                 vector<float> &rowAverage, 
                 datastruct & colAverage)

代码语言:javascript
复制
float getAverage(datastruct list[], 
                 int size,  
                 float rowAverage[], 
                 datastruct & colAverage)

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

代码语言:javascript
复制
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;
    }
};

把它叫做

代码语言:javascript
复制
for (auto & row: list)
{
    rowAverage.push_back(row.getAverage());
    colAverage += row;
}
colAverage /= size;

代码语言:javascript
复制
for(i = 0; i<size; i++)
{
    rowAverage[i] = list[i].getAverage();
    colAverage += list[i];
}
colAverage /= size;

这里,colAverge用于用重载的+=运算符对列表中的所有项进行汇总,然后除以/=运算符的大小。

请注意,在colAverage可以用于求和之前,需要对其进行零化。您可能需要添加一个方法或构造函数来执行此操作。

计算总数是相似的。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35785574

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档