file i/o

so let say i got some numbers like so in a .txt file

1
2
3
4
  12 13 22 22 43 45
  23 54 87 89 98 88
  34 55 76 88  8 88
  45 32 45 28 98 88

i want to write a code to have them from bottom to top in a new .txt file
and with other modifications like so..
1
2
3
4
{45, 32, 45, 28, 98, 88},
{34, 55, 76, 88,  8, 88},
{23, 54, 87, 89, 98, 88},
{12, 13, 22, 22, 43, 45},

because they are going to be passed into a 2 dimensional array and the data is a whole lot to be entering them by hand...

how do i go about such a code, in c++ or c++11?
thanks in advance
Last edited on
because you want to reverse the order of the list you will have to read the entire file into memory first. (you cant write the last one till you've read it).

As its a text file you could just read it into an array of strings.
[url]http://www.cplusplus.com/search.do?q=read+a+text+file[/url]

then start at the last row, tweak the changes and write it to the new file, repeat the process moving up the original data till you get to the top (first one).
[url]http://www.cplusplus.com/search.do?q=save+a+text+file[/url]

take it a step at a time, get each step working so that you can see the data in a debugger.

posting code in these forums will get you a much better response from the community, they like to see people having a go :)
I wrote a sample of the code:

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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include <iostream>
#include <fstream>
#include <cstring>
#include <stdlib.h>
using namespace std;

const int row = 4, column = 6;
void splitData(int [][column], const string& = " ");
void outputArray(const int [][column]);

int main()
{
    int numberArrays[row][column] = {};
    string line;
    ifstream iFile("numbers.txt"); //assuming 'numbers.txt' is in this source code's directory

    if(iFile)
    {
        while(getline(iFile, line))
            splitData(numberArrays, line);

        outputArray(numberArrays);
    }
    else
        cout << "The file could not be found!\n";

    return 0;
}

void splitData(int numberArrays[][column], const string& line)
{
    static int lineLength = line.length(), columnCounter = 0, rowCounter = row - 1;
    char newLine[lineLength + 1];
    char *p;

    for(int i = 0; i < lineLength; i++)
        newLine[i] = line[i];

    newLine[lineLength] = '\0';

    p = strtok(newLine, " ");

    while(p)
    {
        numberArrays[rowCounter][columnCounter++] = atoi(p);
        p = strtok(NULL, " ");
    }

    columnCounter = 0;
    rowCounter--;
}
void outputArray(const int numberArrays[][column])
{
    ofstream oFile("numbers_updated.txt");

    for(int i = 0; i < row; i++)
    {
        for(int j = 0; j < column; j++)
            oFile << numberArrays[i][j] << ' ';

        oFile << endl;
    }
}
Topic archived. No new replies allowed.