Home > database >  Writing results to multiple txt files in C
Writing results to multiple txt files in C

Time:11-27

I have the following code:

#include <fstream>
#include <iostream>

using namespace std;


int main() {
  ofstream os;
  char fileName[] = "0.txt";
  for(int i = '1'; i <= '5'; i  )
  {
     fileName[0] = i;
     os.open(fileName);
     os << "Hello" << "\n";
     os.close();
  }
  return 0;
}

The aim is to write my code output into multiple .txt files up to, say 64 different times. When I change this loop to run more than 10, that is

for(int i = '1'; i <= '10'; i  )

I get the following error:

warning: character constant too long for its type

Any ideas how to write to more than 10 files? Moreover, how do I write a number after each "Hello", e.g. "Hello1 ... Hello10"?

Cheers.

CodePudding user response:

I believe the reason you receive that warning is because you're attempting to assign two chars into one slot of the char array:

fileName[0] = i;

because when i = 10;, it's no longer a single character.

#include <fstream>
#include <iostream>
#include <string>//I included string so that we can use std::to_string

using namespace std;


int main() {
    ofstream os;
    string filename;//instead of using a char array, we'll use a string
    for (int i = 1; i <= 10; i  )
    {
        filename = to_string(i)   ".txt";//now, for each i value, we can represent a unique filename
        os.open(filename);
        os << "Hello" << std::to_string(i) << "\n";//as for writing a number that differs in each file, we can simply convert i to a string
        os.close();
    }
    return 0;
}

Hopefully this resolved the issues in a manner that you're satisfied with; let me know if you need any further clarification! (:

  • Related