如何重载CIN读取文件[复制](How to overload cin to read file [

2019-10-17 09:04发布

可能重复:
操纵输入文件流

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读取文件

Answer 1:

尝试这样的:希望这将是有益的

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


文章来源: How to overload cin to read file [duplicate]