简体   繁体   中英

how to read multiple txt files in c++ in a specified format.?

I have a code in C++ that reads multiple txt files from a directory. But the files are in a specifies format, ie abc01.txt, abc02.txt, abc03.txt....., abc99.txt.

I can read the file in the format, abc1.txt, abc2.txt, abc3.txt....., abc99.txt. Using my code. Problem is i cant read the integer value 01 to 09.

Please help me how can I edit my code and read all the files.

My code:

 for(files=1;files<=counter;files++)
  {   stringstream out;
      out<<files;
       infile="./input/abc"+out.str()+".txt";
              input.open(infile.c_str());
  }

This could be a dirty fix but you could add an additional condition to handle text files abc01 to abc09

 for(files=1;files<=counter;files++)
  {   stringstream out;
      out<<files;
       if(files<10){
       infile="./input/abc0"+out.str()+".txt";
       }
       else
       infile="./input/abc"+out.str()+".txt";
              input.open(infile.c_str());
  } 

You could use std::sprintf to format the string, eg

for (int filenum=1; filenum<=counter; filenum++) {
  char nambuf[64];
  std::snprintf(nambuf, sizeof(nambuf), "./input/abc%02d.txt", filenum);
  std::ifstream infile;
  infile.open(nambuf);

I recommend spending more time reading the documentation of C++ standard library.

You can use the std::setw and std::setfill io manipulators to make sure your number is formatted to be at least two digits long:

for(int file = 1; file <= counter; file++) {
    std::ostringstream filename;
    filename << "./input/abc" << std::setw(2) << std::setfill('0') << file << ".txt";
    std::ifstream input(filename.str());
}

Here inserting std::setw(2) ensures that numbers are formatted to be at least two characters long, and std::setfill('0') fills out any missing characters with '0' when formatting the number.

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