C++:将文件(未知大小的数据)输入向量问题

C++: Input file (data of unknown size) into vector issue

我正在尝试将包含两列数据 x 和 y 的文件放入两个向量中,一个只包含 x,另一个只包含 y。没有列 headers。 像这样:

x1 y1
x2 y2
x3 y3

然而,当我运行这段代码时,我遇到了一个错误:(lldb) 如果我做错了什么,有人可以告诉我吗?

#include <iostream>
#include <cmath> 
#include <vector>
#include <fstream> 

using namespace std;

int main() {

    vector <double> x; 
    vector <double> y; 

    ifstream fileIn;

    fileIn.open("data.txt"); //note this program should work for a file in the above specified format of two columns x and y, of any length.

    double number;

    int i=0;

    while (!fileIn.eof())
    {
        fileIn >> number;
        if (i%2 == 0) //while i = even
        {
            x.push_back(number); 
        }
        if (i%2 != 0) 
        {
            y.push_back(number); 
        }
        i++; 
    }
    cout << x.size();
    cout << y.size();

    fileIn.close();
    return 0;
}

我认为这与您的代码无关。 检查你的 g++

参数
g++ -o angle *.cpp -Wall -lm

如果文件 data.txt 无法打开,程序将进入无限循环,如果您将其终止(使用 Ctrl+C),消息 "lldb" 是调试器的名称。你应该这样写:

fileIn.open("data.txt"); //note this program ...
if(!fileIn) { // check if fileIn was opened
    cout << "error opening data.txt\n";
    return 1;
}

看看。 另外,

while (!fileIn.eof())

不是读取文件的正确方法。看: Reading a C file, read an extra line, why?