Im trying to write a C program where the number of character
I\'m trying to write a C++ program where the number of characters in each word of a text file is counted. I\'m having trouble defining in my loop exactly when a word begins and ends (using characters). How can I reword this loop so that it recognizes a word and adds the number of characters in it to the variable called \"word?\" Here\'s what I have so far:
 #include <iostream>
 #include <fstream>
 #include <string>
 using namespace std;
 int main(){
 ifstream fin(\"file.txt\");
 int word=0;
 char ch;
 while(fin && ch!= \'.\'){
   if(ch==\' \' || ch==\'\ \')
    word++;
 //It is wrong because the end of text may have large portions of blank spaces which, by this loop, would be counted as chars in a word
Solution
// C++ code
#include <iostream>
 #include <fstream>
 #include <string>
 using namespace std;
int main()
 {
 string word;
 int sum=0;
 int characters;
 ifstream fin ;
 fin.open(\"file.txt\");
while(!fin.eof())
 {
 // read word
 fin >> word;
// count characters in word
 characters= word.length();
   
 cout << word << \" => \" << characters << endl;
// add characters to sum
 sum=characters+sum;
 }
cout << \"Number of characters in file: \"<< sum << endl;
return 0;
 }
/*
 file.txt
 his style deploys a lack of conventional paragraphing .
output:
 his => 3
 style => 5
 deploys => 7
 a => 1
 lack => 4
 of => 2
 conventional => 12
 paragraphing => 12
 . => 1
 Number of characters in file: 47
*/


