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

标签 c++ vector text-files fstream

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

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 < 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?

关于c++ - 从制表符分隔文件中读取二维数据并存储在 vector C++ 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33551634/

相关文章:

java - 两个不同长度 vector 的欧氏距离

c# - 我怎么知道文本文件是否以回车结尾?

java - 文本文件行读取器 - java

c++ - 按值赋值运算符不使用显式复制构造函数编译

c++ - 这个 operator[] 函数的实现是如何工作的?

c++ - 指针问题(可能很简单)

java - 查找最相似的 List<String> 的有效方法

c++ - 如何编写 Const 和 Mutable 重载代码?

c++ - OpenCV 2.4.3 到 2.4.9 版本变更

c# - 如何将控制台屏幕记录到文本文件中?