I’m currently trying to write a program which will read words from a text file. Finally I plan to read certain words from a file and so on but at the moment I can’t get my current code to work.
I have 3 files. Header file, main file and implementation file.
ReadWords.h
#ifndef READWORDS_H
#define READWORDS_H
/**
* ReadWords class. Provides mechanisms to read a text file, and return
* capitalized words from that file.
*/
using namespace std;
#include <string>
#include <fstream>
class ReadWords
{
public:
/**
* Constructor. Opens the file with the default name "text.txt".
* Program exits with an error message if the file does not exist.
*/
ReadWords();
/**
* Constructor. Opens the file with the given filename.
* Program exits with an error message if the file does not exist.
* @param filename - a C string naming the file to read.
*/
ReadWords(char *filename);
/**
* Closes the file.
*/
void close();
// working storage.
private:
string nextword;
ifstream wordfile;
bool eoffound;
};
#endif
ReadWords.cpp
#include "ReadWords.h"
#include <iostream>
using namespace std;
//:: Defines function as member of class.
ReadWords::ReadWords(char *filename)
{
ifstream str;
str.open("hamlet.txt");
char c;
while ((c = str.get()) !=EOF){
cout << c << endl;
}
}
void close()
{
}
main.cpp
#include "ReadWords.h"
int main()
{
ReadWords rw;
rw.ReadWords("hamlet.txt");
}
Now I know I’m clearly doing something wrong, but I’m not 100% sure what.
The error I receive in compilation is as follows:
main.cpp: In function `int main()':
main.cpp:6: error: invalid use of `class ReadWords'
Tool completed with exit code 1
Any help is greatly appreciated. 🙂
In your main.cpp, you missed the quotes in the
#include ReadWords.hdirective. To fix this you should use#include "ReadWords.h".Also, you should note that
std::istream::getreturns only a character. If you want to read a whole word in a (for example)std::string, you should usestd::istream::operator >>like this:Another thing that stands out is that in
rw.ReadWords("hamlet.txt")you’re calling a constructor as if it were a member function. The proper way to use that overload is:ReadWords rw("hamlet.txt").As a side note: the constructor’s job is to initialize the object. It’s not a good practice to do more than that inside it’s body.