Reading a file with a supplied name in C++
Posted
by
Cosmina
on Stack Overflow
See other posts from Stack Overflow
or by Cosmina
Published on 2012-11-17T10:56:40Z
Indexed on
2012/11/17
11:00 UTC
Read the original article
Hit count: 302
I must read a file with a given name (it's caled "hamlet.txt"). The class used to read the file is defined like this
#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);
My definition of the members of the classis this:
#include<string>
#include<fstream>
#include<iostream>
#include "ReadWords.h"
using namespace std;
ReadWords::ReadWords()
{
wordfile.open("text.txt");
if( !wordfile )
{
cout<<"Errors while opening the file!"<<endl;
}
}
ReadWords::ReadWords(char *filename)
{
wordfile.open(filename);
if ( !wordfile )
{
cout<<"Errors while opening the file!"<<endl;
}
wordfile>>nextword;
}
And the main to test it. using namespace std; #include #include
#include "ReadWords.h"
int main()
{
char name[30];
cout<<"Please input a name for the file that you wish to open";
cin>>name;
ReadWords x( name[] );
}
When I complie it gives me the error: main.cpp:14: error: expected primary-expression before ']' token
I know it's got something to do with the function ReadWords( char *filename), but I do not know what. Any help please?
© Stack Overflow or respective owner