-

2011年8月2日星期二

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_ifstre鈥?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!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).

没有评论:

发表评论