5

I am new to programming, so I have what is probably a basic question. I currently have a text file with 2 columns. Each line has x and y numbers separated by white spaces. These are the first five lines of the file:

120 466
150 151
164 15
654 515
166 15

I want to read the data and store them into x and Y columns and then call for the data some where else in the program for eg x[i] and y[i]. Say, I do not know the number of lines. This is the part of my code where I attempt to do just that.

#include <fstream>
#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int main()
{
    double X[];
    double Y[];

    ifstream inputFile("input.txt");
    string line;

    while (getline(inputFile, line))
    {
        istringstream ss(line);

        double x,y;

        ss >> x >> y;
        X = X + [x];
        Y = Y + [y];

        return 0;
    }
}
Abdul
  • 79
  • 2
  • 7
  • 1
    This is a duplicate question, that coincidentally I have already answered in depth. Check it out http://stackoverflow.com/questions/40307840/reading-file-content-opened-with-ifstream/40309722#40309722 and let me know if it helps, it should. It pertains to the specific problem you are having. – Nick Pavini Oct 31 '16 at 18:49
  • 1
    This is a duplicate question, I would recommend reading up on this http://stackoverflow.com/questions/7868936/read-file-line-by-line it should be easier since you are a beginner and already implements some of the same functionality you have. – I'm here for Winter Hats Oct 31 '16 at 18:53
  • 2
    @user5468794 This is not a duplicate problem because he wants to store into separate containers. – Jonathan Mee Oct 31 '16 at 19:06
  • Think about using a structure to contain X and Y, then use an `std::vector` of those structures. If you are really good, you could figure out how to use `std::pair` and not write a structure. – Thomas Matthews Oct 31 '16 at 19:46
  • @NickPavini that is not the same thing that was asked in this question. – Adan Vivero Jan 14 '22 at 21:25

2 Answers2

5

the good thing to do is use vector:

vector<double> vecX, vecY;
double x, y;

ifstream inputFile("input.txt");

while (inputFile >> x >> y)
{
    vecX.push_back(x);
    vecY.push_back(y);
}

for(int i(0); i < vecX.size(); i++)
    cout << vecX[i] << ", " << vecY[i] << endl;
Raindrop7
  • 3,889
  • 3
  • 16
  • 27
0

The recommended way would be to use a std::vector<double> or two (one for each column) because values can be easily added to them.

sim642
  • 751
  • 7
  • 14