0

I have been trying to read data from a text file which contains float data in two columns

1 2
3 4
4.5 6.5
2 4

Now, I have tried the methods of several questions in stackoverflow like this, this and some others. The final code that I have written is:

#include<iostream>
#include<fstream>
#include<string>
#include<vector>

using namespace std;


int main()
{
    vector<float> a, b;

    fstream file;
    file.open("sample.txt", ios::in);
    if(!file){
        cout << "Error" <<endl;
        return 0;
    }
    
    int number_of_lines = 0;
    string line;

    while(getline(file,line))
    {   
        file >> a[number_of_lines];
        file >> b[number_of_lines];
    }

    cout << number_of_lines << endl;

    for (int i = 0; i < number_of_lines; i++) //code to print out the vectors
    {
        cout << a[i] << " " << b[i] <<endl;
    }

    return 0;
}

But it doesn't seem to work. What can I do read the data in vectors?

Mockingbird
  • 115
  • 4

1 Answers1

2

(Update): All you need is:

float ai, bi;
while (file >> ai >> bi) {
  a.push_back(ai);
  b.push_back(bi);
  number_of_lines++;
}
0x499602D2
  • 87,005
  • 36
  • 149
  • 233