如何重载cin来读取文件

时间:2012-11-12 18:47:38

标签: c++ operator-overloading

  

可能重复:
  Manipulate Input File Stream

C ++如何重载cin来读取文件

我正在尝试以下操作符重载...

struct myself
{
string myname;
}

istream &operator>> (istream &stream, myself &mm)
{
cout << "Enter my name:";
stream >> mm.myname;
return stream;
}

int main()
{
myself mm;
cin >> mm;

cout << mm.myname;

}

及其工作,能够回应我实际输入的内容。

现在我试着继续

cout << "Enter file name to read: ";

//assume user type myfile.txt

cin >> readFile;

如何重载我的cin以使其成为读取文件。

考虑我的文件是

包含

等数据的sometextdocument.txt
Map2D, [3, 2]
Dot3D, [25, -69, -33], [-2, -41, 58]
Map3D, [6, 9, -50]
Map2D, [3, 2]
Dot3D, [7, -12, 3], [9, 13, 68]
Map3D, [6, 9, 5]
Map2D, [3, 2]
Dot3D, [70, -120, -3], [-29, 1, 268]
Dot3D, [7, 12, 3], [-9, 13, 68]
Map3D, [1, 3, 8]
Dot2D, [5, 7], [3, 8]

然后我想要cout << "Number of records read: " << number << endl; 然后做一个返回流,我如何重载它作为cin读取文件

1 个答案:

答案 0 :(得分:-2)

试试这样:希望它会有所帮助

istream &operator>> (istream &in, char* fname){ 
  inFile.open(fname);
  char ch1;
  while (inFile.get(ch1)) {
       cout<<ch1;
  }
}