Trouble with ifstream
Here's my code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
class Text {
public:
string fileText;
Text(){}
Text(string fileName){
ifstream in(fileName);
string line;
while(getline(in, line))
fileText += line + "\n";
}
string contents(){ return fileText; }
};
int main(){
Text test("exercise7.1.cpp");
string output = test.contents();
cout << output << endl;
return 0;
}
|
I get the following error on line 12:
C:\CodeBlocks\Exercises\Chapter 7\exercise7.1.cpp||In constructor `Text::Text(std::string)':|
C:\CodeBlocks\Exercises\Chapter 7\exercise7.1.cpp|12|error: no matching function for call to `std::basic_ifstream<char, std::char_traits<char> >::basic_ifstream(std::string&)'|
C:\CodeBlocks\MinGW\bin\..\lib\gcc\mingw32\3.4.5\..\..\..\..\include\c++\3.4.5\iosfwd|90|note: candidates are: std::basic_ifstream<char, std::char_traits<char> >::basic_ifstream(const std::basic_ifstream<char, std::char_traits<char> >&)|
C:\CodeBlocks\MinGW\bin\..\lib\gcc\mingw32\3.4.5\..\..\..\..\include\c++\3.4.5\fstream|524|note: std::basic_ifstream<_CharT, _Traits>::basic_ifstream(const char*, std::_Ios_Openmode) [with _CharT = char, _Traits = std::char_traits<char>]|
C:\CodeBlocks\MinGW\bin\..\lib\gcc\mingw32\3.4.5\..\..\..\..\include\c++\3.4.5\fstream|509|note: std::basic_ifstream<_CharT, _Traits>::basic_ifstream() [with _CharT = char, _Traits = std::char_traits<char>]|
||=== Build finished: 1 errors, 0 warnings ===|
|
What am I doing wrong with ifstream?
You need to use a c string to open files, so use fileName.c_str().
Thanks, that worked.
A C-string is just a character array, right?
Yes.
Topic archived. No new replies allowed.