【问题标题】:Reading pairs of doubles from file (C++)从文件中读取双精度对(C++)
【发布时间】:2014-03-27 12:39:25
【问题描述】:

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

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

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

【问题讨论】:

  • 您遇到的具体问题是什么?
  • 您显示的输入的第一个方法works perfectly on ideone (link)
  • 嗯,我不确定问题出在哪里,但这可能与文本文件是在 Linux 上创建而我在 Windows 上编码的事实有关,这与不同换行符?我不知道。在修改输入文件后,它现在似乎可以工作了,而代码保持不变。

标签: c++ file stream double std-pair


【解决方案1】:

试试这个 -

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;

}

【讨论】:

    猜你喜欢
    • 2016-06-10
    • 1970-01-01
    • 2011-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多