0

I'm trying to read a global istream* using the following code:

/*Global Declaration*/
istream* fp;

/* in main */
ifstream iFile;
if(argc == 2)
  //open file code
  fp = &file;
else
  fp = &cin;
readFile;

/*readFile*/
readFile(){
  string line;
  while(fp.getline(line))
    cout<<line<<endl;
}

I'm getting the following error code: "request for member getline in fp, which is of non-class type `std::istream*' Could anyone tell me what the error is, and if there's a better way to go about it? I did try getline(fp, line) but had more errors there too.

  • 1
    You're looking for `std::getline`, not `std::istream::getline`, by the way. – chris Oct 03 '13 at 18:14
  • 1
    `.` != `->` , similarly, `std::getline(fp, line)` != `std::getline(*fp, line)`. – WhozCraig Oct 03 '13 at 18:15
  • I did try that, and got the following error:no matching function for call to `getline(std::istream*&, std::string&) I assume there's a problem with how I'm declaring and assigning the file pointer, but I'm not sure how else to do it that works. – user2278604 Oct 03 '13 at 18:16
  • BTW, no need to make `fp` pointer. You can simply use reference as: `auto & fp = argc==2? file : cin;`. Now `fp` is a reference. – Nawaz Oct 03 '13 at 18:18
  • Doesn't Zac Howland's solution works? – demonking Oct 03 '13 at 18:18

1 Answers1

2

You are declaring fp as a pointer, but trying to use it as an instance. Your readfile function should look like this:

void readFile()
{
    string line;
    while(std::getline(*fp, line)) // note the de-referencing of fp
    {
        cout<<line<<endl;
    }
}

(You also have several other syntax errors in your code that I'm assuming are just typos).

Zac Howland
  • 15,777
  • 1
  • 26
  • 42
  • I see. Yes, I was trying to pull only the relevant bits from several files, so it came out a bit messy, sorry about that. Thanks for the help. I guess I need to brush up on pointers again. – user2278604 Oct 03 '13 at 18:18