如何在c++中分割一行并从中提取值

How do I split a line and extract values from it in C++?

本文关键字:一行 提取 c++ 分割      更新时间:2023-10-16

我在编写程序的一部分时遇到了麻烦,该程序将从文件中读取一个名称和10个数字。数据文件的结构是:

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

使用标准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>>