C ++:从文件中读取x y数据会产生无限循环吗?

我正在尝试编写一个C ++代码,该代码读取具有x-y数据的文件(如下所示的示例文件)

1.0,10.0
2.0,10.0
3.0,20.0
4.0,20.0
5.0,10.0
6.0,10.0

由于这些是实验数据,因此当我将所有数据放入数组时,我制作了一个结构,使读取起来更容易。我成功打开了文件。但是,当我创建一个将数据放入数组的循环时,我陷入了无限循环。我该如何解决?另外,有没有一种方法可以动态分配数组(也许是向量)的大小,该大小会根据文件长度自动更改呢?

我的代码如下:

#include <iostream>
#include <fstream>
#include <istream>

struct point{
    float x,y;
};


int main(void)
{
    std::string input_fn = ("testdata.txt");
    std::string output_fn = ("output.txt"); 

    std::ifstream input_data;  
    input_data.open(input_fn.c_str());                              //opening an input file
    while(input_data.fail()){                                       //checking if file exists
        input_data.close();
        std::cout << "Incorrect filename,try again\n";
        std::cin >> input_fn;
        input_data.open(input_fn.c_str()); 
    }

    //float x[2000];
    //float y[2000];
    point pttable[2000];

    int i = 1;
    input_data.clear();                                             // clear stream flags and error state
    input_data.seekg(0,std::ios::beg);
    while (!input_data.eof()){                                      //this is the faulty infinite loop                          
    input_data >> pttable[1].x >> pttable[1].y;
    std::cout<<i;
    i++;
    }
    delete &i;

    input_data.close();

return 0;
}
oliver112233 回答:C ++:从文件中读取x y数据会产生无限循环吗?

在这种情况下,读操作可能会失败,它将设置故障位,而不必设置eof位。因此建议循环直到读取失败。在StackOverflow上有多个帖子,解释何时使用EOF。

希望这些参考资料会有所帮助。

Differences between eof and fail

How does ifstream's eof() work?

将错误的while循环替换为:

while(true)
{
    if(!(input_data >> pttable[1].x >> pttable[1].y))
        break;

    std::cout<<i;
    i++;
}
本文链接:https://www.f2er.com/3096574.html

大家都在问