c++ - 从带有空格分隔符的文本文件中将对象读入数组

标签 c++ oop filestream ifstream

美好的一天,

我正在尝试将数据从文件读取到对象数组中。我似乎找不到如何处理空格分隔符。请帮助我。

该类称为Rational,它有两个属性:numdenom

文件数据: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;
}

提前致谢。

最佳答案

函数 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.

关于c++ - 从带有空格分隔符的文本文件中将对象读入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59099359/

相关文章:

C++ ASIO : async_accept() handler throws exception when server destroys

oop - 清洁架构 - Robert Martin - 用例粒度

c# - Stream.Read 正在组合两个不同的读取

.net - 何时使用 Using 语句

oop - 是否有专门用于实体组件编程的语言?

linux - 目标是从显示信息中提取视频驱动程序版本,然后将其与支持的版本列表进行比较

c++ - 如何在没有 <array> 的情况下声明具有统一类型的元组?

尝试包含微小的 obj 加载程序头文件时出现 C++ 链接器错误

c++ - 二叉搜索树叶数问题

c++ - 为什么要创建一个只有一个成员的类,即 operator()?