Gautam Goyal
Gautam Goyal

Reputation: 237

passing ifstream object to function and use getline() in between

I want to open a file named 1.board by calling a function and use getline function to print it's characters to new line.But this is showing a lot of errors.

#include <iostream>
#include <string>
#include <vector>
#include <fstream>
using std::ifstream;
using std::cout;
using std::string;
using std::vector;

void ReadBoardFile(ifstream& search)
{
  string line;
  search.open("1.board");
  while(getline("1.board",line))
  {
    cout<<line<<"\n";
  }
}

int main() {
  ifstream fin;
  ReadBoardFile(fin);
}

I don't know what i'm doing wrong.I just can't find a perfect and exact answer. Help,if you can.Thanku!!!!!

Upvotes: 0

Views: 625

Answers (1)

john
john

Reputation: 88017

So here's your code rewritten so it works.

Two changes, first the first parameter to getline should be the stream you are reading from not the name of a file. I'm guessing that you just weren't concentrating when you wrote that.

Second change, I've moved the stream variable search so that it is local to your ReadBoardFile function. There's no reason in the code you've posted to pass that in as a parameter. You might want to pass the name of the file as a parameter, but I'll leave you to make that change.

void ReadBoardFile()
{
  ifstream search("1.board");
  string line;
  while(getline(search,line))
  {
    cout<<line<<"\n";
  }
}

int main() {
  ReadBoardFile();
}

Upvotes: 1

Related Questions