CoddityTeam / movaicode

Concours mensuel du Pire Développeur de France
123 stars 10 forks source link

cpp / unnecessary file i/o #19

Closed chris-codd closed 2 years ago

chris-codd commented 4 years ago

movaicode.cpp

#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;

/**
 * Reverses a given string _s based on a tactless file i/o and streams approach
 * For each character of _s, creates a file and writes the character into it
 * Then reads a character in all the files starting from the latest created, appends it to a string stream and deletes the files
 * Please excuse my inability to produce a deeply bad code : I am re-learning cpp
 * With more time I would add an unnecessary vector + iterator to keep the filenames of the created files
 * And with even more time a inappropriate database, like a graph one
 */

string dumb_reverse (string _s);

int main () {
    cout << dumb_reverse("All your base are belong to us") << endl;
    return 0;
}

string dumb_reverse (string _s) {
    // File output stream
    ofstream fileOutput;
    // File input stream
    ifstream fileInput;
    // Size of the string to reverse
    string::size_type i;
    // Filename
    ostringstream sFilename;
    // Stream on the reversed string
    ostringstream sReversed;

    sReversed.str("");

    // Browse the string to be reversed
    for (i = 0; i < _s.size(); i++) {
        // Build a filename
        sFilename << "movaicode_" << i << ".txt";

        // Open the file, dump a character and close the file
        fileOutput.open (sFilename.str());
        fileOutput << _s[i];
        fileOutput.close();
        // Clear the filename stream
        sFilename.str("");
    }

    // Browse again, because we pretty much like it
    for (i = _s.size(); i > 0; i--) {
        char ch;

        // Build a filename
        sFilename << "movaicode_" << i-1 << ".txt";

        // Open the file, read its content and close the file
        fileInput.open (sFilename.str());
        fileInput >> noskipws >> ch;
        sReversed << ch;
        fileInput.close();
        // Delete the file now useless
        remove(sFilename.str().c_str());
        // Clear the filename stream
        sFilename.str("");
    }

    return sReversed.str();
}

To run it:

$ g++ -o movaicode.exe movaicode.cpp  && ./movaicode.exe
> su ot gnoleb era esab ruoy llA
louismarslen commented 3 years ago

Cher Christopher, j'ai le plaisir et l'honneur de t'annoncer que tu n'as PAS gagné le concours MOVAI CODE. Ce qui fait de toi un EKSSELAN Codeur.

SPOILER : j'espère qu'on aura le plaisir de recevoir ta participation à l'episode 2 du MOVAI CODE (stay tuned).

Bravo toutefois pour ta belle contribution 😊

louismarslen commented 2 years ago

Je fais un peu de ménage dans les issues -> d'ailleurs go participer à l'édition 5