reading a datafile within a programme

Hello again all,

first of all, thanks for all the replies that I have received earlier, they really help me as i am a beginner! My problem is as follows:

I have a data file as follows:

1 x1 y1 z1
2 x2 y2 z2
3 x3 y3 z3
....

and I would like my program to read a file and arrange my coordinates as follows:

x1 y1 z1 x2 y2 z2 x3 y3 z3 ...

and then analyse it with the rest of the code that I have.

I am not quite sure how I could do this and thank for any suggestions in advance!
You could use the vector class which can hold strings as elements, but you might find it to be too complicated. I suggest reading about the vector class:

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
#include<vector>
#include<cstdlib>
#include<iostream>
#include<fstream>

using namespace std;

int main()
{
    int i,j=0;
    string holder;
    ifstream infile;
    infile.open("test.txt");
    vector<string>data(9,"0"); /*Declares a vector called data that hold 9 elements
of type string, and initializes each string to 0.*/
    for(i=0;i<12;i++)
    {
        infile>>holder;
        if(i%4!=0) //If i/4 has a remainder that is not equal to zero...
        {
            data[j]=holder;
            j++;
        }
    }
    for(i=0;i<9;i++)
        cout<<data[i]<<" ";
    cout<<endl<<endl;
    system("pause");
    return 0;
}


My text file looked like this:

1 x1 y1 z1
2 x2 y2 z2
3 x3 y3 z3

EDIT: If you don't want to use the vector class, you can just replace line 1 with #include<string> and line 14 with string*data=new string [9];. It achieves the same effect.

Last edited on
Topic archived. No new replies allowed.