简体   繁体   中英

Reading 2D data from tab delimited file and store in vector C++

I am trying to read a text file of the format:

5
1.00   0.00
0.75   0.25
0.50   0.50
0.25   0.75
0.00   1.00

The code is:

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

int totalDataPoints; // this should be the first line of textfile i.e. 5
std::vector<double> xCoord(0); //starts from 2nd line, first col
std::vector<double> yCoord(0); //starts from 2nd line, second col
double tmp1, tmp2;

int main(int argc, char **argv)
{
    std::fstream inFile;

    inFile.open("file.txt", std::ios::in);

    if (inFile.fail()) {
        std::cout << "Could not open file" << std::endl;
        return(0);
    } 

    int count = 0;

     while (!inFile.eof()) { 
         inFile >> tmp1;
         xCoord.push_back(tmp1);
         inFile >> tmp2;
         yCoord.push_back(tmp2);
         count++;
     }

     for (int i = 0; i < totalDataPoints; ++i) {
         std::cout << xCoord[i] << "    " << yCoord[i] << std::endl;
     }
    return 0;
}

I am not getting results. My final aim is to put this as function and call the x, y values as an object of a class.

int totalDataPoints; is a global variable and since you are not initializing it with a value it is going to be 0 initialized. Then in your for loop

for (int i = 0; i < totalDataPoints; ++i) {
     std::cout << xCoord[i] << "    " << yCoord[i] << std::endl;
}

You are going to do anything since i < totalDataPoints ( 0 < 0 ) is false . I suspect you meant to use

for (int i = 0; i < count; ++i) {
     std::cout << xCoord[i] << "    " << yCoord[i] << std::endl;
}

Or have

totalDataPoints = count;

Before the for loop.

I would also suggest you do not use while (!inFile.eof()) to control the reading of the file. To fix it You can use

 while (inFile >> tmp1 && inFile >> tmp2) { 
     xCoord.push_back(tmp1);
     yCoord.push_back(tmp2);
     count++;
 }

This will ensure the loop will only run while there is data to read. For more information see: Why is “while ( !feof (file) )” always wrong?

Just a simple change needed in your code. You can not take totalDataPoints which is provide from file.txt in first line. Then you take every line until reach last.

int count = 0;

    inFile>>totalDataPoints;

     while (!inFile.eof()) {
         inFile >> tmp1;
         xCoord.push_back(tmp1);
         inFile >> tmp2;
         yCoord.push_back(tmp2);
         count++;
     }

By for loop you can do this like, Here int count = 0 is unnecessary:

inFile>>totalDataPoints;

    for (int i=0; i<totalDataPoints; i++)
    {
        inFile >> tmp1;
         xCoord.push_back(tmp1);
         inFile >> tmp2;
         yCoord.push_back(tmp2);
    }

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