简体   繁体   English

我的 C++ Loop 工作不正常,我不明白为什么

[英]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:我正在尝试编写一个程序,将(从 input.txt 文件)复制 30 行到一个文件,然后循环并将接下来的 30 行复制到第二个文件,然后将接下来的 30 行复制到第三个文件,等等。这就是我为尝试实现这一目标而写的:

#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.谢谢大家。

The problem is that you are opening and closing the output file once per line, instead of once every 30 lines.问题是您每行打开和关闭输出文件一次,而不是每 30 行一次。

I suggest that you restructure your program to use a nested loop.我建议您重构程序以使用嵌套循环。 The outer loop should handle one output file (ie 30 lines) per loop iteration, and the inner loop should handle a single line per loop iteration.外循环应在每次循环迭代中处理一个输出文件(即 30 行),而内循环应在每次循环迭代中处理一行。

Here is an example:这是一个例子:

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

int main()
{
    std::ifstream input( "input.txt" );
    std::string line;
    int fileNum = 0;
    bool finished = false;

    std::cout << "Initialized\n";    

    //process one file per loop iteration
    for ( int fileNum = 0; !finished; fileNum++ )
    {
        //open new output file
        std::ofstream outFile("frames/frame" + std::to_string(fileNum) + ".mcfunction");

        //process one line per loop iteration
        for ( int i = 0; i < 30; i++ )
        {
            if ( !std::getline(input, line) )
            {
                finished = true;
                break;
            }

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

        //add schedule and scoreboard commands to bottom of each file
        outFile << "scoreboard players set Frame: BadApple " + std::to_string(fileNum) << '\n';
        outFile << "schedule frame" + std::to_string(fileNum + 1) + ".mcfunction 5s\n";
    }

    return 0;
}

Note that in my code above, I have removed using namespace std;请注意,在我上面的代码中,我已经删除了using namespace std; , for the reason described here: ,出于此处描述的原因:

Why is "using namespace std;"为什么“使用命名空间标准;” considered bad practice?被认为是不好的做法?

Also, you should generally only use std::endl if you want to actually flush the buffer.另外,如果你想真正刷新缓冲区,你通常应该只使用std::endl Otherwise, you can simply print "\n" , which is better for performance.否则,您可以简单地打印"\n" ,这样可以提高性能。 See the following question for further information:有关详细信息,请参阅以下问题:

"std::endl" vs "\n" “std::endl” 与 “\n”

I have therefore removed std::endl from the program.因此,我从程序中删除了std::endl

You keep reopening the file on every iteration of the loop.您在循环的每次迭代中不断重新打开文件。 So then it keeps overwriting the first line.所以它会不断覆盖第一行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM