Miscalculating words/spaces
I was suppose to create a programs that reads out all characters, spaces, and words in a txt file, also a word would be anything followed by a space and also includes punctuation marks as words.
So far I have done everything that I am suppose to, but running the txt file under certain circumstances such as "space.space" in creates double words this is my code so far.
Code:
#include <fstream>
#include <iostream>
#include <conio.h>
#include <cctype>
using namespace std;
int main()
{
char ch,oldch;
int cnt_ch=0, cnt_words=0, spacenum=0;
ifstream poemfile;
poemfile.open("F:\\Super Computer programming\\Roses.txt");
if( poemfile.fail() )
{
cout<<"The File could not be found. Terminating\n";
getch();
exit(1);
}
ch = poemfile.get();
while( !poemfile.eof() )
{
cout<<ch;
cnt_ch++;
ch=poemfile.get();
if(ch == ' ')
{
spacenum++;
}
if ((ch == ' ') && (oldch != ' ') ) cnt_words ++;
if ((ch == '?') || (ch == '.') || (ch == '!'))
{
cnt_words++;
}
}
poemfile.close();
cout<<"\nThe file had "<<cnt_ch
<<" characters, "<<spacenum
<<" spaces, and "<<cnt_words+1
<<" words\n";
cout<<"\n\nNormal termination.\n";
getch();
return 0;
}
Re: Miscalculating words/spaces
This code
Quote:
Originally Posted by
raulian
Code:
if ((ch == '?') || (ch == '.') || (ch == '!'))
{
cnt_words++;
}
contradicts the statement
Quote:
Originally Posted by
raulian
...a word would be anything followed by a space and also includes punctuation marks as words.
Re: Miscalculating words/spaces
Indentation shouldn't be random. Your code would be a lot easier to read and debug if it were formatted better.
You're checking for the value in oldch, but you're never setting it anywhere.