从文本文件中读取,使用c ++使用函数进行数学运算

时间:2018-02-20 05:01:16

标签: c++ function input

这是我应该做的正式描述:

编写一个程序,从文本文件中读取整数(整数)(制作自己的文本 整个数字的文件在不同的行上)。您必须输出以下信息 到屏幕: a)有多少偶数? b)有多少奇数? c)文件中所有数字的总和和平均值。 您必须在程序中具有以下功能。 •用于打开传递文件流变量作为参考参数的文件的函数。 •一个函数,用于从文件中读取数字并将值传递给下一个函数 •此函数称为分类,将计算偶数和奇数并保持 积累总和。 Sum,evenCount和oddCount必须传递给此函数 引用。 •主要测试上述功能并完成其余工作。

我在这个程序上遇到了很多麻烦。我到目前为止的代码是:

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

using namespace std;


int oFile();
int readNum();
int classify();

int main() 
{
    oFile();
    classify();
    int sum, evenCount, oddCount;



    return 0;
}

int oFile()
{
    string inputFileName;
    ifstream inputFile;

    cout << "Input the file name: ";
    getline(cin, inputFileName);

    //open file
    inputFile.open(inputFileName);


    if (!inputFile.is_open())
    {
        cout << "Unable to open file" << endl;
        exit(1);
    }


}

int readNum() {
ifstream inputFile;
    int i;
    while (inputFile >> i) {
        cout << "The value from file is: " << i << endl;
    }
    return 0;
}


int classify()
{
ifstream inputFile;
    int sum = 0, even = 0, odd = 0, x = 0, sumcount = 0;
    while (inputFile.peek() != EOF)
    {
        cout << "Next integer in file: " << x << endl;
        sum = sum + x;
        sumcount++;
        if (x % 2 == 0)
            even++;
        else
            odd++;
    }

    return sum;

}

当我运行这个程序时,系统会提示我输入一个文件名,但是当我输入文件名时,我的数字已满,我的if语句运行并说无法打开文件。我不知道从这里开始使用这个程序,我对功能很新,所以任何帮助都会在进步中受到赞赏。你可以注意到我还没有完成这个程序。我的主要问题是让所有函数在彼此之后顺利运行,我不知道如何调用这些函数来使程序正常运行。另一个问题是我不知道如何调用用户在函数中输入的文件名。我想我要问的是:如果有人可以为我需要的每个功能编写骨架代码。谢谢。

0 个答案:

没有答案