1

I'm trying to write a program which will create/output multiple files in a folder within a loop, but gives me errors. Is something like this possible to do? Been searching with no luck. Thanks! Here's an example:

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    ofstream text;
    for(int i = 0; i < 100; i++);
    {
        text.open("folder/" + i + ".txt");
        text << "This is text file #" << i << "."<< endl;
        text.close();
    }
return 0;
}
3
  • 1
    std::string file_path = std::string("folder/") + std::to_string(i) + ".txt" Commented Sep 18, 2015 at 7:16
  • std::to_string gives an error? :( Commented Sep 18, 2015 at 7:30
  • Compile with -std=c++11 flag. Commented Sep 18, 2015 at 7:35

2 Answers 2

1

You are trying to add const char * and a number, which is not possible. And this is not what you want. Instead you should do following in your loop

ofstream text;
for(int i = 0; i < 100; i++);
{
    string str;
    str = "folder/";

    std::stringstream ss;
    ss << i; //convert int to stringstream

    str += ss.str(); //convert stringstream to string 
    str + =  ".txt";

    text.open(str); //use final string
    text << "This is text file #" << i << "."<< endl;
    text.close();
} 

Do not forget to include #include <sstream>.

Sign up to request clarification or add additional context in comments.

7 Comments

I think std::stringstream` for one int number instead of std::to_string is a little overkill.
@Satus Actually I read above comment. Not sure to_string works for C++ 98. Because many people still not started with C++ 11/14.
It does not work for C++98. But, well, there is no reason not to use C++11 in 2015.
@Satus Completely agreed. But just wanted to stay relevant with lot of programmer. But your solution is more accurate as per new C++ standard.
@VardanBetikyan Happy to help.
|
0

You can't concatenate a simple string and convert a number int string just by writing

  "folder/" + i + ".txt";

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    ofstream text;
    for(int i = 0; i < 100; i++);
    {
        stringstream FileName;
        FileName<<"folder/"<<i<<".txt;
        text.open(FileName.str().c_str());
        text << "This is text file #" << i << "."<< endl;
        text.close();
    }
    return 0;
 }

I have created the string stream within the loop. Doing so a new string stream is created with each loop and destroyed at the end of the loop Same would work, when you declare the stringstream outside of the loop. But that case you have clear the stringstreeam at the end of each loop

2 Comments

The "FileName" after stringstream gives me an error :( (Red lining)
And what does the compiler tell when you try to compile?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.