Given a string (or a char* pointing to the first letter), is it possible to return the whole word, knowing the length?
I cannot edit the .h file. The function I need help with is GetWord() in class Word. Right now, it only returns the first letter, but I need it to return the whole word.
#include "words.h"
#include <iostream>
#include <string>
#include <istream>
#include <fstream>
#include <ostream>
usingnamespace std;
constint FILE_PATH_SZ = 512;
Word** wordArray;
int arrSz;
//@opens an input file and checks for errors
void openFile(ifstream& infile, string filename);
//@gets the number of words in the file and
//@makes arrSz equal to that number
int getSize(ifstream& infile, string filename);
void makeArray(ifstream& infile);
int main()
{
ifstream infile;
ofstream outfile;
string filename;
//cout << "Enter a filename to open: ";
//cin >> filename;
filename = "sample.txt";
openFile(infile, filename);
arrSz = getSize(infile, filename);
cout << "The array is " << arrSz << endl;
makeArray(infile);
return 0;
}
//@opens an input file and checks for errors
void openFile(ifstream& infile, string filename)
{
infile.open(filename.c_str());
if (infile.fail())
{
cout << "Error in opening the input file." << endl;
cout << "Ending program now." << endl;
exit(1);
}
}
//@gets the number of words in the file and
//@makes arrSz equal to that number
int getSize(ifstream& infile, string filename)
{
string oneItem;
int count = 0;
infile >> oneItem;
while (!infile.eof())
{
infile >> oneItem;
count++;
}
infile.close();
infile.open(filename.c_str());
return count;
}
void makeArray(ifstream& infile)
{
string newWord;
wordArray = new Word*[arrSz];
for(int j = 0; j < arrSz; j++)
{
infile >> newWord;
wordArray[j] = new Word(newWord.c_str());
cout << wordArray[j]->GetWord() << ", "; // I used this to test GetWord()
}
}
sample.txt
1 2 3 4 5 6 7 8
so much depends upon
a red wheel barrow
glazed with rain water
beside the white
chickens
is the problem. You create and copy only one char here. The right way would be
1 2 3
ptr = newchar[strlen(word)+1];
memcpy(ptr, word, strlen(word)+1);//or a for loop that copies every char..
len = strlen(word);//you don't really need this, but if you must..
Also, what are lines 6, 7 of Words.cpp supposed to do? I'm not sure, but they may be breaking your code too..