【问题标题】:Parsing a string inside a vector c++解析向量c ++中的字符串
【发布时间】:2015-01-24 20:39:56
【问题描述】:

我有一个文本文件:

bob,10,20,30
joe,50,60,50
shelly,20,15,29

我想读入一个学生类型的向量,定义:

   class student
    {

      public:
        string name;
        int exam1;
        int exam2;
        int exam3;

            student (string s, int x, int y, int z)
            {
              name = s;
              exam1 = x;
              exam2 = y;
              exam3 = z;
            }
    };

使用迭代器 begin() 和 end(),我可以逐行存储字符串,但我希望能够解析这些字符串以存储学生姓名和他/她的考试成绩,但我没有不知道能不能搞定。

我从字符串类中读到了“find”和“substr”,但总的来说,我对迭代器和向量有点陌生。当它是类型时,如何使用“find”和“substr”解析向量?我知道我的代码或想法中可能已经有很多错误。

主要:

int main()
{
  //Open file and create iterator
  ifstream file ("test.txt");
  istream_iterator<string> begin (file), end;

  vector<student> vec (begin, end);
}

【问题讨论】:

标签: c++


【解决方案1】:

为了让标准 C++ 库为您解析字符串,请为 student 类提供自定义输入运算符 &gt;&gt;

istream &operator >>( istream &input, student &res ) {
    string s;
    int x, y, z;
    char comma; // Ignored
    getline(input, s, ',');
    input >> comma >> x >> comma >> y >> comma >> z;
    res = student(s, x, y, z);
    return input;
}

此实现的效率低于预期,因为它需要复制。您可以通过直接写入student 的字段来提高效率,因为它们是公开的:

istream &operator >>( istream &input, student &res ) {
    getline(input, res.name, ',');
    char comma; // Ignored
    input >> comma >> res.exam1 >> comma >> res.exam2 >> comma >> res.exam3;
    return input;
}

最后,您可以将字段设为私有,并将operator &gt;&gt; 声明为friend 类的friend

【讨论】:

  • 当我尝试您的第二个示例时,我收到错误 'std::istream& student::operator>>(std::istream&, student&)' must take exactly one argument
  • @filposs 我认为这是因为您在类中声明了运算符,而没有将其设为类的friend。一旦你将它标记为friend,它就会变成非成员,并且可以使用第二个参数。有关信息,请参阅this Q&A
猜你喜欢
  • 1970-01-01
  • 2017-04-10
  • 2014-01-06
  • 2019-12-10
  • 2011-02-15
  • 1970-01-01
  • 2015-03-23
  • 1970-01-01
相关资源
最近更新 更多