Циклический просмотр текстового файла и вывод различных данных в C ++ - PullRequest
1 голос
/ 07 октября 2019

Мой код просит меня преобразовать:

2 6 2 // # of quizzes (2), homeworks(6), exams(2)
Solution Key 10 10 10 10 20 20 20 20 100 100
Washington George 10 10 10 10 20 20 20 20 100 100
Jefferson Thomas 10 0 8 6 20 15 13 0 80 90
Franklin Benjamin 0 0 0 0 20 10 20 10 100 50
Lincoln Abraham 10 5 10 5 0 0 0 0 80 30
Madisonville James 5 7 9 3 10 12 14 16 0 0
Wilson Woodrow 2 4 6 8 10 12 14 16 74 89
Hoover Herbert 0 10 10 10 0 20 20 20 0 100
Roosevelt Franklin 0 0 0 0 0 0 0 0 0 0

В это (в выходном файле):

#  Last        First  Quiz  HW    Exam  Total  Average 
-  ----------  -----  ----  ---   ----  -----  -------
   Solution    Key    20    100   200   320    100.00
-  ----------  -----  ----  ---   ----  -----  -------
1  Washington  Georg  20    100   200   320    100.00
2  Jefferson   Thoma  10    62    170   242    75.62
3  Franklin    Benja  0     60    150   210    65.62
4  Lincoln     Abrah  15    15    110   140    43.75
5  Madisonvil  James  12    64    0     76     23.75
6  Wilson      Woodr  6     66    163   235    73.44
7  Hoover      Herbe  10    80    100   190    59.38
8  Roosevelt   Frank  0     0     0     0      0.00
-  ----------  -----  ----  ---   ----  -----  -------

Class Average = 55.20

Я использовал циклы с контролем количества для получения теста, домашние заданияи результаты экзаменов, однако мой вывод выглядит следующим образом:

  #  Last        First  Quiz   HW   Exam  Total  Average
  -  ----------  -----  ----   ---  ----  -----  -------
  -  ----------  -----  ----   ---  ----  -----  -------
  -  ----------  -----  ----   ---  ----  -----  -------

Class Average = 1458176112

Вот мой код:


#include <fstream>
#include <iostream>
#include <iomanip>
#include <cstring>
#include <climits>
#include <typeinfo>
using namespace std;

//Sample solution
//- /home/work/cpe211/Executables/Project_06/Project_06_solution
//Comparison script
//- /home/work/cpe211data/Project_06/CompareSolution.bash Project_06.cpp


int main(int argc, char* argv[])
{
    if (argc != 3) // if the amount of arguments is greater than 2, perform this.
    {
        cout << endl;
        cout << "Incorrect number of command line arguments provided. \n";
        cout << "This program requires 2 command line arguments: \n";
        cout << "An input filename and an output filename \n \n";
        cout << "Program usage is: \n";
        cout << "./Project_06 InputFileName OutputFileName \n \n";
        return 1;
    }


    // Variable Delcaration
    ifstream inFile; // input
    ofstream outFile; // output
    string inputFileName, outFileName;
    string line1, line2, line3, first, last;
    int quiznum, homenum, examnum, quiz, homework, exam, total, average, total_sol, count_quiz, count_exam, count_homework, count, homework_total, exam_total, quiz_total, average_p2, average_total;

    // ***** Opening and naming command line argument ***** //
    inputFileName = argv[1]; // assign command line argument value to a string variable
    inFile.open(inputFileName.c_str());
    cout << "Opening Input File: " << inputFileName << endl;
    outFile.open(argv[2]);
    cout << "Opening Output File: " << argv[2] << endl;

    // ***** Testing to see if the file exists ***** //
    while (inFile.fail()) // if the file does not exist, then do this.
    {
        cout << endl;
        cout << string(15,'*') << " File Open Error " << string(15,'*') << endl;
        cout << "==> Input file failed to open properly!!\n";
        cout << "==> Attempted to open file: " << inputFileName << endl;
        cout << "==> Please try again...\n";
        cout << string(47,'*') << endl << endl;
        inFile.clear(); // clears the input file stream
        cout << "Enter the name of the input file: ";
        cin >> inputFileName; // user inputs new name of file
        inFile.open(inputFileName.c_str()); // opens the new input file
        cout << inputFileName << endl; // echo prints the new input file name
        cout << "Opening Output File: " << argv[2] << endl; // echo the output fule

    }

    // ***** Testing for output file existance ***** //
    while (outFile.fail()) // if the file does not exist, then do this.
    {
        cout << endl;
        cout << string(15,'*') << " File Open Error " << string(15,'*') << endl;
        cout << "==> Output file failed to open properly!!\n";
        cout << "==> Attempted to open file: " << argv[2] << endl;
        cout << "==> Please try again...\n";
        cout << string(47,'*') << endl << endl;
        outFile.clear();
        cout << "Enter the name of the output file: ";
        cin >> outFileName; // recieves input for the new output file name
        outFile.open(outFileName.c_str()); // opens the output file
        cout << outFileName << endl; // echo prints new output file name
    }


    // ***** First line information ***** //
    getline(inFile,line1,'\n'); // gets line 1
    inFile >> quiz >> homework >> exam; // retrieves number of quiz, homework, and exam scores from the first line.
    if (inFile.eof())
    {
        cout << endl;
        cout << "*************" << " Input File Is Empty " << "*************" << endl;
        cout << "==> The input file is empty.\n";
        cout << "==> Terminating the program.\n";
        cout << string(47,'*') << endl << endl;
        outFile << "Input file " << inputFileName << " is empty. \n";
        return 1;
    }


    // ***** Count initializers ****** //
    count = 0;
    count_quiz = 0;
    count_homework = 0;
    count_exam = 0;


    // ***** Starting for output ***** //
    outFile << "  #  " << "Last        " << "First  " << "Quiz  " << " HW   " << "Exam  " << "Total  " << "Average" << endl; // First line info for each part of the file
    outFile << setw(3) << "-" << setw(12) << "----------" << setw(7) << "-----" << setw(6) << "----" << setw(6) << "---" << setw(6) << "----" << setw(7) << "-----" << setw(9) << "-------" << endl; // seperating dashes


    // ***** Sample solution data ***** //
    getline(inFile,line2,'\n');
    while (inFile >> last >> first)
    {
        while (count_quiz < quiz)
        {
            inFile >> quiz;             // gets the quiz scores
            quiz_total = quiz + quiz;   // total of all quiz scores
            count_quiz++;
        }
        while (count_homework < homework)
        {
            inFile >> homework;
            homework_total = homework + homework;
            count_homework++;
        }
        while (count_exam < exam)
        {
            inFile >> exam;             // gets exam scores
            exam_total = exam + exam;   // totals all exam scores found
            count_exam++;               // updates count
        }

        total_sol = quiz_total + homework_total + exam_total; // total score for solution set
        average = (total_sol / total_sol) * 100; // average for solution set (100%)
        outFile << last << first << quiz_total << homework_total << exam_total << total_sol << average << endl; // output of all the above info
    }
    outFile << setw(3) << "-" << setw(12) << "----------" << setw(7) << "-----" << setw(6) << "----" << setw(6) << "---" << setw(6) << "----" << setw(7) << "-----" << setw(9) << "-------" << endl; // seperating dashes


    // ********* The following grabs the info from each line using count controlled loops ********* //
    getline(inFile,line3,'\n'); // gets the new lines
    while (inFile >> last >> first)
    {
        while (count_quiz < quiz) // while the count is less than the number of the quizzes, do this.
        {
            getline(inFile,line3,'\n');         // gets line 3 and updates each time
            inFile >> quiz;                     // quiz scores
            quiz_total = quiz + quiz;           // total of all the quiz scores
            outFile << quiz_total;              // output for total quiz scores
            count_quiz++;                       // updates count
        }
        while (count_homework < homework) // while the count is less than the number of specified homeworks, do this
        {
            getline(inFile,line3,'\n');         // gets line 3 and updates each time
            inFile >> homework;                 // homework scores
            homework_total = homework + homework; // total of all homework scores
            outFile << homework_total;          //  output for total homework scores
            count_homework++;                   // updates count
        }
        while (count_exam < exam) // while the count is less than than the number of specified exams, do this.
        {
            getline(inFile,line3,'\n');         // gets line 3 and updates each time
            inFile >> exam;                     // exam scores
            exam_total = exam + exam;           // total of all exam scores
            outFile << exam_total;              // output for total exam scores
            count_exam++;                       // updates count
        }
        outFile << last << first << quiz_total << homework_total << exam_total << endl;
        total = quiz_total + homework_total + exam_total; // total # of quiz, homeworks, and exam scores added
        average_p2 = total / average; // average for each student
        average_total = (average_p2 + average_p2) / count; // total average for all students
    }

    outFile << setw(3) << "-" << setw(12) << "----------" << setw(7) << "-----" << setw(6) << "----" << setw(6) << "---" << setw(6) << "----" << setw(7) << "-----" << setw(9) << "-------" << endl << endl; // seperating dashes
    outFile << "Class Average = " << average_total << endl; // outputs the total average of the exam.


    outFile.close();
    return 0;
}


TLDR: Как мне пройти по текстовому файлу и получить его информацию,использовать их в расчетах и ​​правильно выводить?

...