Hi, I have questions regarding to this topic to count the words from the input file. for example, if the words inside the file "Give me everything"
It will be counted as 3.
void fillList (list <char> &myList, const string &strings);
void printList (const list<char> &myList);
int countChar (const list <char> &myList);
int countWord (list <char> &myList);
int main (int argc, char *argv[])
{
string strings;
list <char> myList;
ifstream file (argv[1]);
if (argc != 2) {
cout << "usage: " << argv[0] << " <filename>" <<endl;
return 0;}
else
{
if (!file.is_open())
{
cout << "Could not open file " << argv[1] << endl;
return 1;
}
else
{
file.eof();
getline(file, strings);
}
}
fillList(myList, strings);
printList(myList);
countChar(myList);
countWord(myList);
}
void fillList (list <char> &myList, const string &strings) //This is to fill the list with the strings inside the file
{
for (int i = 0; i < strings.length(); i++)
myList.push_back (strings[i]);
}
void printList (const list<char> &myList) //This method is to print anything in the list
{
list<char>::const_iterator itr;
int countChar (const list <char> &myList)
{
list<char>::const_iterator itr;
int count = 0;
for (itr = myList.begin(); itr != myList.end(); itr++ ) {
count ++;
}
cout << "Number of graphical characters are " << count << "\n";
return count;
}
int countWord (list <char> &myList)
{
list<char>::iterator itr;
int count = 0;
char current = *itr;
for (itr = myList.begin(); itr != myList.end(); itr++)
{
if (current == ' ') // I think here is the part where it gives error
count ++;[/b]
}
cout << "Number of words are " << count << "\n";
return count;
}
When I tried run the code it says segmentation fault (core dumped).
The purpose of this program is to count how many words in the text file.
I tried with reading characters, and now I am trying to do with counting words.
So the logic is whenever the iterator returns the character and equal to space, comma, or any special characters, it starts counting.