0

For a clustering program I am writing, I need to read information from a file. I am trying to read coordinates from a file with a specific format:

1.90, 2
0.0, 4.01
6, 1.00

Unfortunately, I have not been able to do this, because of the newlines and dots that are present in this file. Neither of the following two functions work, even though the filestream is "good":

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;
}

I have no idea how to fix this and any help is greatly appreciated.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Knaapje
  • 165
  • 1
  • 1
  • 10
  • What exactly is the problem you are experiencing? – David G Mar 27 '14 at 12:45
  • 2
    Your first method [works perfectly on ideone (link)](http://ideone.com/1bNKHA) for the input that you show. – Sergey Kalinichenko Mar 27 '14 at 12:50
  • Hm, I'm not sure what the problem was, but it might have to do with the fact that the text file was created on Linux and I was coding on Windows, something to do with the different newlines? I have no idea. It seems to work now, after fiddling with the input file, while the code remained the same. – Knaapje Mar 27 '14 at 20:01

1 Answers1

0

try this one -

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;

}

Idan Yehuda
  • 524
  • 7
  • 21