使用空格分隔符从文本文件中将对象读取到数组中

美好的一天,

我正在尝试将文件中的数据读取到对象数组中。我似乎找不到解决空间定界符的方法。请帮助我。

该类称为 Rational ,它具有两个属性: num denom

文件数据: 1/2 -1/3 3/10 4/5 6/18

到目前为止,我已经做到了:

int operator>>(ifstream& fin,rational r[]) {

    fin.open("filedata.txt",ios::in);
    if (fin)
    {    
        for (int i = 0; i < 5; i++)
        {
            fin >> r[i];
        }
    }
    else
    {
        cout << "\nData file cannot be found!" << endl;
    }
}

ifstream& operator>>(ifstream& in,rational& r)
{
    int num,denom;
    char slash;
    in >> num >> slash >> denom;
    r.set(num,denom);
    return in;
}

谢谢。

xiangzhy 回答:使用空格分隔符从文本文件中将对象读取到数组中

函数operator>>(ifstream& in,rational& r)应该按发布的方式工作,尽管我将其更改为

std::istream& operator>>(std::istream& in,rational& r) { ... }

但是,第一个功能不正确。即使函数的返回类型为int,您也不会返回任何内容。您可以将其更改为:

int operator>>(ifstream& fin,rational r[])
{
    int count = 0;
    fin.open("filedata.txt",ios::in);
    if (fin)
    {    
        for ( ; count < 5; ++count)
        {
            // If unable to read,break out of the loop.
            if ( !(fin >> r[count] )
            {
               break;
            }
        }
    }
    else
    {
        cout << "\nData file cannot be found!" << endl;
    }
    return count;
}

话虽如此,我认为您可以对该功能进行一些改进。

  1. 可以在调用函数main中打开文件,然后将std::ifstream对象传递给它。

  2. 与其传递数组,而不是传递std::vector。这样,您就不必担心文件中的条目数。您会阅读文件中可以找到的所有内容。

  3. 将返回类型更改为std::istream&,以便在必要时可以链接呼叫。

std::istream& operator>>(std::istream& in,std::vector<rational>& v)
{
   rational r;
   while ( in >> r )
   {
      v.push_back(r);
   }
   return in;
}

main(或更高级别的函数)中,使用:

std::vector<rational> v;
std::ifstream fin("filedata.txt);
if ( !fin )
{
   // Deal with error.
}
else
{
   fin >> v;
}

// Use v as you see fit.
本文链接:https://www.f2er.com/3009777.html

大家都在问