0

I have a code in C++ that reads multiple txt files from a directory. But the files are in a specifies format, i.e 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()); } 
0

3 Answers 3

1

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()); } 
Sign up to request clarification or add additional context in comments.

1 Comment

Brutal but simple. Can avoid the stringstream with std::to_string.
0

You could use std::sprintf to format the string, e.g.

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.

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.