HI Guys,
I have been having lots of issues not understanding why this isn't working.
I'm trying to
1. Read the contents of the file into the string object
2. Add a member function contents() to return the string so that you can display it.
When I compile I get the error below...
TMA2-3.cpp:63:20: error: expected primary-expression before 'tc'
cout << textClass tc("File_TMA2-3.txt").contents;
I'm not even sure if that's the way it should be done. Isn't "tc" just referring to the instantiation of the class object? Any help is appreciated.
#include <iostream>
#include <string>
#include <fstream>
struct text_class {
text_class() = default ;
explicit text_class( const std::string& file_name ) {
if( std::ifstream file{file_name} ) { // if file was opened successfully
// read each character in the file and append to text
char c ;
while( file.get(c) ) text += c ;
}
else {
// failed to open file
}
}
const std::string& contents() const { return text ; }
private: std::string text ;
};
int main() {
const std::string this_file = __FILE__ ;
std::cout << text_class(this_file).contents() ;
}
1. ifstream f(filename) should be ifstream(filename.c_str())
2. The file is very much in the cwd.
I'm getting an error regarding the contents function...I'm not sure why when I'm not trying to convert it to an int.
1 2 3
TMA2-3.cpp: In member function 'int textClass::contents()':
TMA2-3.cpp:29:11: error: cannot convert 'std::__cxx11::string {aka std::__cxx11::basic_string<char>}' to 'int' in returnreturn text;
If you require .c_str() when opening a filestream then you need to upgrade your compiler (or turn c++11 features on).
You haven't declared the return type of contents(). Don't you think that you ought to before the compiler makes an incorrect assumption? Presumably it is string contents() {