Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

Reading a file with C++ using a function.?

I'm having some trouble with a C++ function i created. I can read from the file just fine, but when I put it in a function (read_file, in this case), I can't compile. Is there something I'm missing? it looks correct, but I'm really new to C++ and could use a little assistance.

I'm trying to return a string from the read_file function. I have tried going the read_file(string s) route by giving a string ("Boat.txt") and using ifstream file(s) but it gives me similar errors.

Error:

Files.cpp: In function 'int main()':

Files.cpp:22:25: note: synthesized method 'std::basic_ifstream<char>::basic_ifstream(const std::basi

c_ifstream<char>&)' first required here

Files.cpp:22:25: error: initializing argument 1 of 'std::string read_file(std::ifstream)'

Pastebin: //http://pastebin.com/8gmEfVta

Code:

#include <iostream>

#include <fstream>

using namespace std;

string read_file(ifstream file)

{

string s;

if(file.is_open()) {

while(file.good()) {

string l;

getline(file,l);

s = s + l + "\n";

}

}

return s;

}

int main()

{

ifstream f("Boat.txt");

string s1 = read_file(f);

cout << s1 << endl;

return 0;

}

Like I said, if I do this in main(), I have no trouble. It's just when I put it into a function and try to return a string from it, it stops compiling.

Thanks for the help!

2 Answers

Relevance
  • Merc
    Lv 6
    10 years ago
    Favorite Answer

    Change "read_file(ifstream file)" to "read_file(ifstream &file)".

    That's called "passing by reference" (it's like pointers). Otherwise C++ is trying to create a new ifstream object, but it can't do this because a stream is not copyable (i.e., it doesn't have a (public) copy constructor).

  • Anonymous
    5 years ago

    the first parameter is the name of the textfile that you are reading from. Try a full path if it cannot find the file, you will have to use double backslash like C:\\file.txt.

Still have questions? Get your answers by asking now.