I wrote a program that creates a text file with some letters using ofstream. Now I would like to format the text so that the letters are written in groups of 5 and the rows are all the same length( i.e. DANIWEBFORUM becomes DANIW EBFOR UM). To do this the fprintf function seemed the most appropriate. in the following example I use integers, but it is just an example.

#include <string>
#include <iomanip>
#include <fstream>
#include <cstdio>

using namespace std;

int main()
{
    ofstream f;
    
    f.open("testo.txt");
    
    for(int i = 0; i < 21; i++)
    {
            f << i;  
            }
            
    f.close(); //to simulate file already created
    
    FILE *file;
    int number;
    file = fopen("testo.txt", "r+");
    if (file==NULL) perror ("Error opening file");
    else
    {
        do {
           number = fgetc (file);
           fprintf(file, "%-5.5i", number);
        } while (number != EOF);
     }
     fclose(file);
     return 0;
}

can this method work? or there is some function that I can use directly when creating the file with ofstream?
please help

When you say letters, do you mean characters? Your code example is showing numbers.
I would suggest you EITHER use iostream OR the standard library, but not both.

Will the input file contain carriage-returns?

On the output, how many columns will there be on each row?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.