从制表符分隔文件中读取二维数据并存储在矢量 C++ 中

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

我正在尝试读取以下格式的文本文件:

5
1.00   0.00
0.75   0.25
0.50   0.50
0.25   0.75
0.00   1.00

密码是:

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

我没有得到结果。我的最终目标是将其作为函数并将 x、y 值作为 class.

的对象调用

int totalDataPoints; 是一个全局变量,并且由于您没有使用值对其进行初始化,因此它将被初始化为 0。然后在你的for循环中

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

因为 i < totalDataPoints(0 < 0) 是 false,所以你会做任何事情。我怀疑你打算使用

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

或有

totalDataPoints = count;

在 for 循环之前。

我也建议你不要使用while (!inFile.eof())来控制文件的读取。修复它你可以使用

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

这将确保只有在有数据要读取时才会运行循环。有关详细信息,请参阅:Why is “while ( !feof (file) )” always wrong?

只需对您的代码进行简单的更改。您不能在第一行中使用 file.txt 提供的 totalDataPoints。然后你走每一行直到到达最后。

int count = 0;

    inFile>>totalDataPoints;

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

通过for循环你可以这样做,这里int count = 0是不必要的:

inFile>>totalDataPoints;

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