Sep 28, 2013 at 4:35pm UTC
My program is not reading the number of words correctly when I enter a sentence. For example, when I type in the sentence: "To Build Something, First You have to Tear it off", my output says 9 words instead of 10. How can I fix this? Thank you for any help!
#include <iostream>
#include <ctime>
#include <cctype>
using namespace std;
int main ()
{
time_t P;
time (&P);
cout << "Today's time and date is: " << ctime(&P) << endl;
int Nl=0, Nd=0, Nw=0, Nv=0; char c;
cout << "Enter a sentence: \n";
while (cin.get(c), c!='\n')
{
//Counts letters
if(isalpha(c)) Nl++;
//Counts digits
if(isdigit(c)) Nd++;
//Counts words
if(isspace(c)) Nw++;
//Finds vowels
if(isalpha(c));
switch(c)
{
case 'a': case 'e': case 'i': case 'o': case'u':
case 'A': case 'E': case 'I': case 'O': case 'U':
Nv++;
break;
}
}
//Displays results
cout << "No. of letters............" << Nl << endl;
cout << "No. of digits............." << Nd << endl;
cout << "No. of words.............." << Nw << endl;
cout << "No. of vowels............." << Nv << endl;
//Terminates program
system ("pause");
return 0;
}
Last edited on Sep 28, 2013 at 4:38pm UTC
Sep 28, 2013 at 4:39pm UTC
That's because the computer starts counting from 0, not 1. remember indexing always starts from 0, so 10 words means 9, 20 words means 19 and so on...