Уровень C ++ выше уровня чтения файла и основного контейнера - PullRequest
0 голосов
/ 05 декабря 2018

самоучка.Ищете идеи о более продвинутых способах решения этой простой проблемы с готовым кодом.

Проблема. Считайте файл с именем pair2.txt и выполните уравнение, результаты которого будут опубликованы на экране, а новый файл - output.txt.

Любые идеи приветствуются.В прошлом это помогло мне применить новые идеи к старому простому коду, который я написал, чтобы продвинуться вперед, и я надеюсь на то же самое здесь.

#include <iostream>
#include <iomanip>
#include <fstream>
#include <array>

#define ARRAY_SIZE 150 // number of words expected in data input file, 
change as needed
#define EQUATION( x, y, z )   z == ( (3 * x ) + (7 * y ) - 4 ) ? true : 
false // equation to be checked

// The boolean function checkEquation will accept as input three 
// integers ( points x, y, z ), to be
// computed with the algebraic expression z = ( 3 * x ) + ( 7 * y ) - 4  
// Return true the points make the expression equivalent, otherwise 
// return false.

bool checkEquation( int, int, int );

int main()
{
    // Open file pairs.txt
    std::ifstream inputFile;
    inputFile.open( "pairs2.txt" );
    if ( inputFile.fail() ) // verify input file opened properly
    {
        puts( "\nInput file open failed" );
        return 1;
    }

    std::array < int, ARRAY_SIZE > pairs = {0}; // create array to 
    // place pairs.txt into

    int count = 0; // set a counter for while loop

    // this while loop used to input ints from pairs.txt into 
    // pairs[array] for easy data manipulation
    while (  count < pairs.size() && inputFile >> pairs[count] )
    {
        count++;
    }

    // the following is a code check to verify inputFile was properly 
    // input into array
    // uncomment the next two lines to print array to screen
    // for ( int &val : pairs )
    //    std::cout << val << '\n';

    inputFile.close(); // close pairs.txt

    std::ofstream outputFile( "outputs.txt" ); // create output file 
    // for function results
    if ( outputFile.fail() ) // verify output file opened properly
    {
        puts( "\nOutput file failed to open" );
        return 1;
    }

    bool check_equation_result; // setting bool variable to check array 
    // against function

    // this loop will cycle through the pairs list to determine if 
    // points belong to the pre-defined function
    // and will output the results both to the screen and to file 
    // "outputs.txt" with formatting.
    for ( int k = 0; k < pairs.size(); k += 3 )
    {
        int x, y, z; // setting equation variables
        x = pairs[k]; // each "pair" of points is made up of three 
        // contiguous ints in pairs[array], pairs[0] is the 1st point
        y = pairs[(k+1)]; // 2nd point
        z = pairs[(k+2)]; // 3rd point

        check_equation_result = checkEquation( x, y, z );
        if ( check_equation_result == 0 )
        {
            std::cout << "\nPoint ( " << std::setw(3) << x << ", "
                      << std::setw(3) << y << ", "
                      << std::setw(3) << z << " ) does NOT satisfy the 
                         equation: z = 3x + 7y - 4 ";
            outputFile << "\nPoint ( " << std::setw(3) << x << ", "
                       << std::setw(3) << y << ", "
                       << std::setw(3) << z << " ) does NOT satisfy the 
                          equation:  z = 3x + 7y - 4 ";
        }
        else
        {
            std::cout << "\nPoint ( " << std::setw(3) << x << ", "
            << std::setw(3) << y << ", "
            << std::setw(3) << z << " ) does satisfy the equation:      
                z =   3x + 7y - 4 ";
            outputFile << "\nPoint ( " << std::setw(3) << x << ", "
            << std::setw(3) << y << ", "
            << std::setw(3) << z << " ) does satisfy the equation:      
                z = 3x + 7y - 4 ";
        }
    }
    outputFile.close(); // close outputFile
    puts( "\n" ); // empty line screen output at end of program

    return 0;
}
bool checkEquation( int x, int y, int z )
{
    return EQUATION( x, y, z );  // change EQUATION at #define, 
// HOWEVER, replacement
// equation must use three variables ( x, y, z ) to retain 
// functionality of program.
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...