压缩此代码片段 c++

Condense this code snippet c++

本文关键字:c++ 片段 代码 压缩      更新时间:2023-10-16

我的代码正常运行,但我正在寻找更优雅的解决方案

在这个 for 循环中,我正在解析文件中的一行文本,其中包含用逗号分隔的数据成员。这已存储在vector<str>str

文本文件:

bob,1,2,3
sally,5,8,6
joe,5,1,9

我需要将名称和 3 个相应的分数分别存储在 vector<student> s 中各自的隔间中。

有什么方法可以进一步浓缩这一点吗?

for (string currLine : str)
    {
      int pos = 0;
      int next = 0;
      next = currLine.find (',', pos);
      string name (currLine.substr (pos, next));
      pos = next + 1;
      next = currLine.find (',', pos);
      string expr (currLine.substr (pos, next));
      int a = atoi (expr.c_str());
      pos = next + 1;
      next = currLine.find (',', pos);
      expr = (currLine.substr (pos, next));
      int b = atoi (expr.c_str());
      pos = next + 1;
      next = currLine.find (',', pos);
      expr = (currLine.substr (pos, next));
      int c = atoi (expr.c_str());
      student s (name, a, b, c); //create student with extracted name and scores
      vec.push_back (s); //now push this student onto the vector
    }//end for()

您可以修改流的空格分类,引入"流提取器"(operator>>() ),并使用std::istream_iterator<student>插入到向量中。下面是程序的外观示例:

#include <iostream>
#include <vector>
#include <iterator>
class student_fmt;
struct student
{
    student() = default;
    student(std::string const& name, std::string const& a,
            std::string const& b,    std::string const& c)
        : m_name(name)
        , m_a(a)
        , m_b(b)
        , m_c(c)
    { }
    friend std::istream& operator>>(std::istream& is, student& s)
    {
        if (std::has_facet<student_fmt>(is.getloc()))
        {
            is >> s.m_name >> s.m_a >> s.m_b >> s.m_c;
        }
        return is;
    }
    void display() const
    {
        std::cout << m_name << m_a << " " << m_b << " " << m_c << 'n';
    }
private:
    std::string m_name, m_a, m_b, m_c;
};
class student_fmt : public std::ctype<char>
{
    static mask table[table_size];
public:
    student_fmt(size_t refs = 0) : std::ctype<char>(table, false, refs)
    {
        table[static_cast<int>(',')] |= space;
    }
};
student_fmt::mask student_fmt::table[table_size];
int main()
{
    std::cin.imbue(std::locale(std::cin.getloc(), new student_fmt));
    std::vector<student> v(std::istream_iterator<student>(std::cin), {});
    for (auto& c : v)
        c.display();
}

尝试使用 fstream 和提取运算符。您可以轻松地将输入存储到各个变量中。

    #include <fstream>
    .
    .
    .
    // declare variables
    fstream fin( "fileName.txt", ios::in );
    string name;
    char comma;
    int a, b, c;
    // loop until the end of the file
    while(!fin.eof())
       {
         // get one line of data from the file
         fin >> name >> comma >> a >> comma >> b >> comma >> c;
         // add to your datatype
         student s (name, a, b, c);
         // push into your vector
         vec.push_back (s);
       }