【问题标题】:Reading 2D data from tab delimited file and store in vector C++从制表符分隔的文件中读取二维数据并存储在向量 C++ 中
【发布时间】:2015-11-05 18:01: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 值作为类的对象调用。

【问题讨论】:

标签: c++ vector text-files fstream


【解决方案1】:

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

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

因为i &lt; totalDataPoints(0 &lt; 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?

【讨论】:

  • 是的,它有效。对于 totalDataPoints = xCoord.size();我从文本文件中删除了总分,即 5。现在我可以看到结果了。我怎样才能为此制作一个类文件?
  • @TheCoder 类文件?那是什么?
  • @TheCoder:根据你的输入,它没有维护,它取file.txt cz file.txt 中的第一行是totalDataPoints 5。根据这个代码,你不能拿这个
【解决方案2】:

只需对您的代码进行一个简单的更改。您不能使用第一行中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);
    }

【讨论】:

  • 对于这种特殊情况,可以改进 while 循环 或将其转换为 for 循环,因为我已经知道向量的大小?
  • @TheCoder:是的。当然。你现在破解这个答案。我只是根据你的代码改变。
  • @TheCoder:如果你喜欢这个答案,你可以接受并投票给我。
猜你喜欢
  • 1970-01-01
  • 2020-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-30
  • 1970-01-01
相关资源
最近更新 更多