【问题标题】:Having trouble with calculations with a data file sort使用数据文件排序进行计算时遇到问题
【发布时间】:2013-02-13 21:30:48
【问题描述】:

我是 stackoverflow 社区的新手,也是编码的新手,所以在我了解在这里发帖的技巧以及编码规则时提前道歉。我正在使用 C++,并且正在参加 CS161 初学者计算机科学课程。

我目前正在做一项作业,该作业要求我从存储在我计算机上的数据文件中读取数据并对数据进行排序,以便进行一些计算,在此作业中,计算基于性别和类型的平均测试分数学校的。一切都编译并且程序运行但是有一些问题。

第一个问题是我的回声。

    // echo the data file
    while (inData)
    {
    inData >> name >> sex >> school >> score;
    cout << name << sex << school << score << endl;

程序确实会回显数据,但最终会回显列表中的姓氏,出于某种原因两次。此外,(我不知道这是否重要)当它回显时,它不会跳过姓名、性别、学校和分数之间的空格。

第二个问题是它没有执行计算,我认为这是因为我错过了某种与“计数”相关的指令,但我无法做到。

这是我的代码,让我知道你的想法:

#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
    //Declare variables to manipulate data
    char sex;
    string name;
    string school;
    string fileSource;
    string CC;
    string UN;
    int maleScore = 0;
    int femScore = 0;
    int unScore = 0;
    int ccScore = 0;
    double maleAvg;
    double femAvg;
    double unAvg;
    double ccAvg;
    double sumAvg = 0;
    int femCount = 0;
    int maleCount = 0;
    int ccCount = 0;
    int unCount = 0;
    int score;
    int sum;
    //Declare stream variables
    ifstream inData;
    ofstream outData;
    inData >> name >> sex >> school >> score;
    // Promt user for file location
    cout << "Please input file location: ";
    cin >> fileSource;

    // open output file and run program exit failsafe command
    inData.open(fileSource);
    if (!inData)
    {
        cout << "Cannot open input file. "
            << "Program will now terminate." << endl;
        return 1;
    }
    outData << fixed << showpoint << setprecision(2);

    // echo the data file
    while (inData)
    {
        inData >> name >> sex >> school >> score;
        cout << name << sex << school << score << endl;

        // while reading incoming data from file, execute the conditions

        // Male and female calculations
        if(sex=='M')
        {
            maleScore = maleScore +=score;
            ++maleCount;
        }
        else if(sex =='F')
        {
            femScore = femScore +=score;
            ++femCount;
        }

        // Community college and University calculations
        if(school == CC)
        {
            ccScore = ccScore +=score;
            ++ccCount;
        }
        else if(school == UN)
        {
            unScore = unScore +=score;
            ++unCount;
        }
        maleAvg = maleScore/maleCount;
    }

    // Male average output
    cout << maleAvg;

    femAvg = femScore/femCount;

    // Female average output
    cout << femAvg;

    ccAvg = ccScore/ccCount;

    // Community College average output
    cout << ccAvg;

    unAvg = unScore/unCount;

    // University average output
    cout << unAvg;
    sum = maleScore + femScore + ccScore + unScore;
    sumAvg = sum/12;
    cout << sumAvg;
    return 0;
}

另外,我的编译器会一直运行程序并且不会停止。我拍了一张编译器窗口的照片,但不知道如何发布。

【问题讨论】:

  • 你能给我们看一个应该使用的输入文件的样本吗?
  • 这里是一个例子:Bailey M CC 68。第一列是字符串名称 Bailey,第二列 char M 是性别,第三列字符串 CC 是学校(另一个选项是 UN for university),最后一列 score 是整数 68。文件中有这些的列表。
  • 另外,我将 while (inData) 更改为 while (!inData.eof())。这样更好吗?
  • 我觉得while(inData &gt;&gt; name &gt;&gt; sex &gt;&gt; school &gt;&gt; score)会更好。
  • 谢谢你。尽管如此,即使在做出改变之后,我仍然遇到所有这些问题。没有改变。它仍然没有进行任何计算,并且它仍然一直在运行,直到我手动停止它。但主要是,我关心如何让我的计算运行。有什么想法吗?它看起来很可靠,我不知道为什么它不计算。

标签: c++ if-statement while-loop counter ifstream


【解决方案1】:

您的代码存在一些问题。让我们一次一件地处理,好吗?

ifstream inData;
ofstream outData;
inData >> name >> sex >> school >> score;

最后一行是做什么的? inData 未打开,但您正在尝试从中读取。

maleScore = maleScore +=score;

在这里(以及其他一些地方)您错误地使用了+= 运算符。您应该像这样使用+=

maleScore += score;

或像这样使用+

maleScore = maleScore + score;

然后你这样做:

if(school == CC)

现在,CC 在您的代码中是一个 std::string,您尚未对其进行初始化(这意味着它是空的)。所以它永远不会匹配,因此 if 主体永远不会执行。 UN 也会发生同样的事情。

再往下,循环中有这一行:

maleAvg = maleScore/maleCount;

这样做是在每次循环中重新计算男性的平均值。这不一定是错误的(您会得到正确的结果),但如果文件中的第一个人是女性,您的程序将因除以零而崩溃,因为 maleCount 将为 0。如果没有女性,也会发生同样的事情是否在输入文件中,或者如果没有大学或学院的分数。

最后,在循环中使用iostream::eof() 不是一个好主意。您可以在 StackOverflow 上阅读更多相关信息:Why is iostream::eof inside a loop condition considered wrong?

话虽如此,你的错误并不严重,而且是新程序员的典型错误,所以不要气馁。将此视为学习和了解如何检查代码以查找此类错误的机会。因此,事不宜迟,让我们看看这个程序的改进版本:

#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>

using namespace std; // it's considered bad to do this - but since
                     // this is homework, we'll let it slide.

int main()
{
    //Declare variables to manipulate data    
    string name;
    string fileSource;

    int maleScore = 0;
    int femScore = 0;
    int unScore = 0;
    int ccScore = 0;
    int femCount = 0;
    int maleCount = 0;
    int ccCount = 0;
    int unCount = 0;

    //Declare stream variables
    ifstream inData;
    ofstream outData;

    // Promt user for file location
    cout << "Please input file location: ";
    cin >> fileSource;

    // open output file and run program exit failsafe command
    inData.open(fileSource);

    if(!inData)
    {
        cout << "Cannot open input file. "
             << "Program will now terminate." << endl;
        return 1;
    }    

    cout << "Reading data from '" << fileSource << "'" << endl;

    while(inData >> name)
    { // If we read a name, we can continue. Otherwise, we're done.     
        char sex;       
        int score;
        string school;

        inData >> sex >> school >> score;

        // Write the data out
        cout << "Processing " << name << " (" << sex << ") attending ";

        if(school == "UN")
            cout << "University";
        else if(school == "CC")
            cout << "Community College";

        cout << ". Score = " << score << endl;

        // Male and female calculations
        if(sex=='M')
        {
            maleScore +=score;
            maleCount++;
        }
        else if(sex =='F')
        {
            femScore +=score;
            femCount++;
        }

        // Community college and University calculations
        if(school == "CC")
        {
            ccScore +=score;
            ccCount++;
        }
        else if(school == "UN")
        {
            unScore +=score;
            unCount++;
        }       
    }

    // We do static_cast<double>(maleScore) / maleCount; to ensure that
    // the division is done using floating point and not integer 
    // arithmetic. We could have multiplied the numerator by 1.0 instead.

    if(maleCount != 0)
    {
        cout << "The average scores for males is: " << setprecision(2)
             << static_cast<double>(maleScore) / maleCount << endl;
    }

    if(femCount != 0)
    {
        cout << "The average score for females is: " << setprecision(2)
             << static_cast<double>(femScore) / femCount << endl;
    }

    if(ccCount != 0)
    {
        cout << "The average score for Community Colleges is: " << setprecision(2)
             << static_cast<double>(ccScore) / ccCount << endl;
    }

    if(unCount != 0)
    {
        cout << unScore << "/" << unCount << endl;

        cout << "The average score for Universities is: "  << setprecision(2)
             << static_cast<double>(unScore) / unCount << endl;
    }

    // In this case we will use the multiplication technique instead:   
    cout << "The 'sum' average is: " << setprecision(2)
         << (1.0 * (maleScore + femScore + ccScore + unScore)) / 12 << endl;

    return 0;
}

【讨论】:

  • 哇!你在一次毁灭性的合乎逻辑的打击中解决了我所有的担忧哈哈。我尽我最大的努力看看我可以在那里巩固什么,但我在一个基础课上,所以我们现在才刚刚开始谈论数组。我唯一能够通过设置精度改进的事情。我在计算任何平均值之前放置了这条线: cout
  • 正如我所说,这不是一个坏的努力 - 你是编程新手,在你“进入区域”之前需要一些时间和练习。不要气馁 - 继续插电。我们曾经是所有个新程序员。祝你好运!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-10-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多