从文件中读取双打对(C ++)

问题描述 投票:0回答:1

对于我正在编写的集群程序,我需要从文件中读取信息。我试图从具有特定格式的文件中读取坐标:

1.90, 2
0.0, 4.01
6, 1.00

不幸的是,我无法做到这一点,因为此文件中存在换行符和点。即使文件流“良好”,以下两个函数都不起作用:

std::vector<Point*> point_list_from_file(std::ifstream& ifstr) {
    double x, y;
    char comma;

    std::vector<Point*> point_list;

    while(ifstr >> x >> comma >> y) {
        point_list.push_back(new Point(x,y));
    }

    return point_list;
}

std::vector<Point*> point_list_from_file(std::ifstream& ifstr) {
    double x, y;
    char comma;

    std::vector<Point*> point_list;

    while(ifstr >> x >> comma >> y >> comma) {
        point_list.push_back(new Point(x,y));
    }

    return point_list;
}

我不知道如何解决这个问题,非常感谢任何帮助。

c++ file stream double std-pair
1个回答
0
投票

尝试这个 -

std::vector<Point*> point_list_from_file(std::ifstream& ifstr) {
   char sLineChar [256];
   std::vector<Point*> point_list;
   ifstr.getline    (sLineChar, 256);

   while (ifstr.good()) {
       std::string sLineStr (sLineChar);
       if (sLineStr.length () == 0){
           ifstr.getline    (sLineChar, 256);
           continue;
       }
       int nSep  = sLineStr.Find (',');
       double x = atof (sLineStr.Mid(0,nSep).Trim ());
       double y = atof (sLineStr.Mid(nSep+1).Trim ());
       point_list.push_back(new Point(x,y));
       ifstr.getline (sLineChar, 256);
   }
   return point_list;

}

© www.soinside.com 2019 - 2024. All rights reserved.