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;
    }
}
5
  • 1
    This is a duplicate question, that coincidentally I have already answered in depth. Check it out stackoverflow.com/questions/40307840/… and let me know if it helps, it should. It pertains to the specific problem you are having. Commented Oct 31, 2016 at 18:49
  • 1
    This is a duplicate question, I would recommend reading up on this 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. Commented Oct 31, 2016 at 18:53
  • 2
    @user5468794 This is not a duplicate problem because he wants to store into separate containers. Commented Oct 31, 2016 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. Commented Oct 31, 2016 at 19:46
  • @NickPavini that is not the same thing that was asked in this question. Commented Jan 14, 2022 at 21:25

2 Answers 2

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;
Sign up to request clarification or add additional context in comments.

2 Comments

Really helped a lot. Thank you
@Abdul I believe this is your best solution. If it solved your problem please accept it.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.