简体   繁体   中英

How do I iterate through multiple .txt files in C++ that all follow a similar format?

I have multiple text files that go by the name of "inX.txt", where X represents an integer. I want to go through each of these files (so, in1.txt, in2.txt, in3.txt, etc.), run my code on them, and produce the output files in the same format, so "outX.txt". My code to work on the files works right, as I get the right output when I input each file individually. I want to know how I can go through all input files sequentially. Currently, I am using ifstream to load the input file and ofstream to create and output a file.

Is there any kind of for loop I can use so I can go through as many files as I want to that are in the same format? I am a beginner to C++ and am using Visual Studio.

Edit: I ended up figuring it out (thanks /u/drescherjm). What I did was I just used the to_string() function to convert my loop variable from an int to a string so I can use it in another variable that contains my input and output files.

Within my main() function:

int main() {
  int fileNo = 1;
  while (fileNo < 6) {
    [...]
    std::string fileName = "in" + std::to_string(fileNo) + ".txt";
    std::string fileOut = "out" + std::to_string(fileNo) + ".txt";
    std::ifstream inputfile;
    inputfile.open(fileName);
    [my code that works on the file]
    std::ofstream outputfile(fileOut);
    [my code that prints to the output file]
    inputfile.close();
    outputfile.close();
    fileNo++; //update loop variable
  }
  return 0;
}

I ended up figuring it out (thanks /u/drescherjm). What I did was I just used the to_string() function to convert my loop variable from an int to a string so I can use it in another variable that contains my input and output files.

Within my main() function:

int main() {
  int fileNo = 1;
  while (fileNo < 6) {
    [...]
    std::string fileName = "in" + std::to_string(fileNo) + ".txt";
    std::string fileOut = "out" + std::to_string(fileNo) + ".txt";
    std::ifstream inputfile;
    inputfile.open(fileName);
    [my code that works on the file]
    std::ofstream outputfile(fileOut);
    [my code that prints to the output file]
    inputfile.close();
    outputfile.close();
    fileNo++; //update loop variable
  }
  return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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