fprintf problem (ofstream)

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#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
To do this the fprintf function seemed the most appropriate


It's not though.

Write a function that takes a string and returns a string that has all the characters from the previous string with a whitespace character inserted in every 5th position (I don't think there's a manipulator for that).
closed account (DSLq5Di1)
Mixing C & C++ I/O.. uckk.

1
2
3
4
5
6
7
ifstream input("testo.txt");
char data[6]; // +1 for the null character

while (input.get(data, sizeof data, char_traits<char>::eof()))
{
   // output
}
For a stream based solution using ostream iterators, consider the following thread:
http://www.cplusplus.com/forum/general/7385/
Topic archived. No new replies allowed.