Help counting both words and characters in a loop

Hello, I am trying to create a loop that will read a file containing an array of strings into an array, where I can then edit individual words. I've created a "while" loop that copies the file and counts words, but I want it to keep a count of the total number of characters being read from the file (including spaces " ") as well. That is what the int count is for. Can anyone help me to fix this loop?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
#include <fstream>

using namespace std;
 
 int readFile(char storyText[][32])
{
   cout << "Please enter the filename: ";
   cin >> fileName;

   //open file using filename input by user                                                  
   ifstream fin(fileName);

   //check for errors                                                           
   if (fin.fail())
   {
      cout << "Error opening file \""
           << fileName
           << "\""
           << endl;
   }

   //copy contents of file into array                                           
   int wordCount = 0;
   int count = 0;     //this is the variable I want to include
   while (fin >> storyText[wordCount])
   {
      wordCount++;
   }

   cout << "wordCount: " <<  wordCount << endl;
   cout << "count: " <<  count << endl;

   //don't forget to close file                                                 
   fin.close();
   return;
}

int main()
{
   char storyText[256][32];
   int wordCount = readFile(storyText);

Last edited on
Hello ahoward527,

Untested, but my thought is inside the while loop at line 28
1
2
3
count += storyText[wordCount].length(); // This counts the characters in each word.
wordCount++;
count++; // this counts the spaces between words. 

then before line 31 add count--; // To uncount the space after the last word.

Hope that helps,

Andy
Thanks Andy!
I got it working with a slight adjustment to the code you suggested-
1
2
3
count += strlen(storyText[wordCount]); // for c-strings
wordCount++;
count++; // this counts the spaces between words.  

and including the <cstring> library.
again- thank you for the help!
Topic archived. No new replies allowed.