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

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

本文关键字:存储 C++ 数据 2D 分隔 制表符 文件 读取      更新时间:2023-10-16

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

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值作为类的对象进行调用。

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

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

因为i < totalDataPoints0 < 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++;
 }

这将确保循环只在有数据要读取时运行。有关更多信息,请参阅:为什么"while(!feof(file))"总是错误的?

只需要对代码进行简单的更改。你不能拿第一行file.txt提供的totalDataPoints。然后你把每一行都抄到最后。

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

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

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