1

Possible Duplicate:
Manipulate Input File Stream

C++ How to overload cin to read file

I was trying the following with operator overload..

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;

}

and its work, able to echo out what i actually type.

Now i trying to proceed with

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

//assume user type myfile.txt

cin >> readFile;

How do i overload my cin to make it read file.

Consider my file is something like

sometextdocument.txt that contains data like

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]

And then i wanna cout << "Number of records read: " << number << endl; then do a return stream, how do i overload it to work as cin read a file

Community
  • 1
  • 1
user1777711
  • 1,334
  • 4
  • 18
  • 29

1 Answers1

-2

Try like this: hope it will be helpful

istream &operator>> (istream &in, char* fname){ 
  inFile.open(fname);
  char ch1;
  while (inFile.get(ch1)) {
       cout<<ch1;
  }
}
Christian Rau
  • 43,206
  • 10
  • 106
  • 177
Grijesh Chauhan
  • 52,958
  • 19
  • 127
  • 190
  • 2
    [Why is iostream::eof inside a loop condition considered wrong?](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – jrok Nov 12 '12 at 19:11
  • 1
    Your solution is to ignore the input stream, [loop on `.eof()`](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong), and try to return 0 instead of `istream&`? Sorry but this is completely broken. – Blastfurnace Nov 12 '12 at 19:13
  • @Blastfurnace please help edit the answer, and also so how do i cout and ask for user input, assume he input mytext.txt , how do I cin with his input so its recognize as a file name. – user1777711 Nov 12 '12 at 19:44
  • @user1777711: I think this direction is basically flawed. There are already overloads for `operator>>(istream&, char *)` and `operator>>(istream&, std::string&)` so trying to extract a filename and then processing a file in one `operator>>` won't work. Prompt for the filename in one step and then open the file and process it in a separate step. – Blastfurnace Nov 12 '12 at 19:51
  • @Blastfurnace , how do i prompt for the filename, then open the file in another step using cin. – user1777711 Nov 12 '12 at 20:00
  • @user1777711: Use `std::cin >> filename` to get the file name, `std:ifstream infile(filename)` to open the file, and pass `infile` to your function or `operator>>` that parses the file. (Basically the answer _ahenderson_ just gave in your duplicate question...) – Blastfurnace Nov 12 '12 at 20:06