如何在C ++中拆分行并从中提取值?

时间:2011-11-21 17:55:22

标签: c++

我在编写程序的一部分时遇到问题,该程序将以名称和文件中的10个数字进行读取。 fie称为grades.dat数据文件的结构是:

Number One
99 99 99 99 99 99 99 99 99 99
John Doe
90 99 98 89 87 90.2 87 99 89.3 91
Clark Bar
67 77 65 65.5 66 72 78 62 61 66
Scooby Doo
78 80 77 78 73 74 75 75 76.2 69

这就是我获取数据的功能,我甚至不确定这是否正确。

void input (float& test1, float& test2, float& test3, float& test4, float& test5, float& test6, float& test7, float& test8, float& test9, float& test10, string& studentname)
{
  ifstream infile;

  infile.open ("grades.dat");
  if (infile.fail())
    {
      cout << "Could not open file, please make sure it is named correctly (grades.dat)" << "\n" << "and that it is in the correct spot. (The same directory as this program." << "\n";
      exit(0);
    }
  getline (infile, studentname);
  return;
}

1 个答案:

答案 0 :(得分:10)

使用标准的C ++习惯用法,一次读取两行(如果不可能则失败):

#include <fstream>
#include <sstream>
#include <string>

#include <iterator>  // only for note #1
#include <vector>    //     -- || --

int main()
{
    std::ifstream infile("thefile.txt");
    std::string name, grade_line;

    while (std::getline(infile, name) && std::getline(infile, grade_line))
    {
        std::istringstream iss(grade_line);

        // See #1; otherwise:

        double d;

        while (iss >> d)
        {
            // process grade
        }
    }
}

注意:如果内部循环(标记为#1)的唯一目的是存储所有等级,那么@Rob建议您可以使用流迭代器:

std::vector<double> grades (std::istream_iterator<double>(iss),
                            std::istream_iterator<double>());

流迭代器与上面的内部while循环做同样的事情,即它迭代double类型的标记。您可能希望将整个向量插入到容器中,该容器包含std::pair<std::string, std::vector<double>>个名称和成绩对。