0

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!!!!!

Gautam Goyal
  • 230
  • 1
  • 4
  • 16
  • What is wrong exactly? Did you try to look for similar questions: https://stackoverflow.com/questions/12133379/c-using-ifstream-with-getline, https://stackoverflow.com/questions/7868936/read-file-line-by-line-using-ifstream-in-c – pptaszni Apr 17 '20 at 10:05
  • Please, have a look into doc. [std::getline()](https://de.cppreference.com/w/cpp/string/basic_string/getline). `std::getline()` expects a stream as 1st arg. but you provided a const C string (`"1.board"`). Shouldn't it be `getline(search, line)`? – Scheff's Cat Apr 17 '20 at 10:13
  • 1
    And, if it still isn't accepted then try `std::getline(search, line);`. I appreciate that you tried to prevent `using namespace std;` but all the `using`s at begin of your code appear more tedious to me than just prefixing all standard stuff just by `std::`. ;-) – Scheff's Cat Apr 17 '20 at 10:16
  • thank u very much.it solved my problem @Scheff – Gautam Goyal Apr 17 '20 at 10:25

1 Answers1

1

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();
}
john
  • 85,011
  • 4
  • 57
  • 81
  • thank u and u were right I was not concentrating at that time. And suppose if I passed the file name as a parameter to the function then how can I receive it? – Gautam Goyal Apr 17 '20 at 10:29
  • @GautamGoyal Like this `void ReadBoardFile(const char* filename) { ifstream search(filename); ...`. – john Apr 17 '20 at 11:30