Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

My C++ Loop is not working Properly, and I can't figure out why

I’m trying to write a program that copies (from an input.txt file) 30 lines to one file, then loops and copies the next 30 lines to a second file, then the next 30 to a 3rd file, etc. etc.
This is what I wrote to try and make that happen:

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

using namespace std;

int main()
{
    // initialize
    ifstream input("input.txt");
    string line;
    int i = 0;
    int fileNum = 0;
    cout << "Initialized";

    // Loop through text file and write to new files
    while (getline(input, line) && i < 30)
    {
        // Write to File
        ofstream outFile("frames/frame" + to_string(fileNum) + ".mcfunction");

        // Write Lines
        outFile << "data modify block " << (i + 1) << " -48 20 HeldItem.Item.tag.display.Name set value '{\"text\":\"" << line << "\"}'" << endl;

        // Increment Counters
        i++;
        if (i == 30)
        {
            //  Add Schedule and Scoreboard Commands to Bottom of Each File
            outFile << "scoreboard players set Frame: BadApple " + to_string(fileNum) << endl;
            outFile << "schedule frame" + to_string(fileNum + 1) + ".mcfunction 5s" << endl;

            // Reset Counter & File Number
            i = 0;
            fileNum++;
            cout << i << " ";

        }
    }

    return 0;
}

But it only ends up copying one line from the input file to each document. Everything seems to be working aside from that.

Any help would be much appreciated, I’ve been trying to debug this for a while now but as a naive beginner, I haven’t gotten very far. Thank you all in advance.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You keep reopening the file on every iteration of the loop. So then it keeps overwriting the first line.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading