我目前正在尝试编写一个从文本文件中读取单词的程序。最后我计划从文件中读取某些单词等等,但目前我无法让我当前的代码工作。
我有 3 个文件。头文件、主文件和实现文件。
读字.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()
{
}
主文件
#include "ReadWords.h"
int main()
{
ReadWords rw;
rw.ReadWords("hamlet.txt");
}
现在我知道我显然做错了什么,但我不是 100% 确定是什么。我在编译中收到的错误如下:
main.cpp: In function `int main()':
main.cpp:6: error: invalid use of `class ReadWords'
工具已完成,退出代码为 1
任何帮助是极大的赞赏。:)