getting data from a file and assigning it to a vector

Hi,

I am trying to create a simple program that does exactly what the title says.

The file I want to get data from is a .txt file, which contains a list of number like:

100.00 200.43
101.23 198.56
102.12 201.87
99.67 198.28
100.54 205.98
99.87 199.34
101.57 202.75
103.10 193.50
101.78 198.33
102.13 204.75
104.56 208.34
106.14 199.50
105.98 200.00

i.e. two columns of numbers of type double separated by a single space.

The operation I want to perform is to store the first column of numbers into a vector, and the second column into another vector.

I know, for example, how to tell C++ to read that file and print it out, but how can I tell him to assign the values in the way I want??

Thank you, any comment or help is appreciated, a sample code would be awesome..

Andrea
Two steps,i suppose
1.read data into two different arrays
2.use function push_back() to read the data in the array into different vector

not hard ,you can make it if you try

lulipeng, why use arrays at all? you can use push_back() from the beggining!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <vector>
#include <fstream>

using namespace std;

int main()
{
     ifstream fin(/*your file name inside ""s*/);
     vector<double> a, b;
     double x;
     while (!ios::eof)
     {
            fin>>x;
            a.push_back(x);
            fin>>x;
            b.push_back(x);
            }
     return 0;
     }
Thanks guys, I will try to use your advice this afternoon and see where I get:)
Ok, the code above seemed not to work until line 11 was changed to

while(fin.good()).

Probably I needed to modify something in a simple way but I am not familiar at all with <fstream> ( I should say with C++ in general...)

Anyway, I think the code now works just fine now with this little modification.

I wanted to do a little extra thing which is to count the number of lines in that same file opened via fstream. I tried using the function gcount i.e. adding a line which says

fin.gcount()

just before the return 0; command. However, when I display fin.gcount by "cout" command, it displays 0, even though the number of lines is definitely not zero.

How can I count how many lines were read (or better, how many values are assigned to the vectors a and b in the code above)??

thanks!

Andrea
Actually I think I just found a way to do it, thanks all!

Topic archived. No new replies allowed.