简体   繁体   中英

Store a .txt file columns into an array in c++

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;
    }
}

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;

推荐的方法是使用std::vector<double>或两个(每列一个),因为可以很容易地将值添加到它们中。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM