Hello, I'm a C++ student trying to finish an assignment. My level of knowledge is pretty basic. The assignment requires the program to count the amount of words in an input file. My logic was to have it count the amount of spaces and then adding one more in order to know the total amount of words in the file. I was able to open the file and count the total amount of characters but I'm stuck on the part where it should count a specific character, in this case the space character. My teacher recommended this website. If someone could at least point me in the right directions as to what I'm doing wrong. I would really appreciate any help. Thank you.
int main ()
{
cout<<"This program will search for a word in file and provide the user with ";
cout<<"the amount of times it appeared and the percentage occurrence compared with other ";
cout<<"words in the file.\n";
ifstream in;
string InputFile;
cout<<"Enter the full path the input file: ";
getline(cin,InputFile);
cin.sync();
in.open(InputFile.c_str());
if(in)
{
cout<<"File opened successfully.\n";
int counter = 0;
char Spaces;
while(in)
{
in>>Spaces;//retrieve the characters
while(isspace(Spaces))//Testing for the space character
{
counter ++;
}
}
cout<<"The amount of words in the file is "<<counter<<".\n";
}
else
{
cout<<"File did not open.\n";
}
return 0;
}[/code]
also, I would say in = Spaces.get... I don't know if there's a real difference, but I prefer that method
(in other words you don't have to change for it to work =)
oh and you may wish to reevaluate your if(in) check.
edit: oh and you don't need a while loop for your isspace function.
int counter = 0;
string whatever;
while (in >> whatever) {
counter++;
}
counting the spaces should work also. there's a couple good ways to do it that i can think of
if (someChar == 32) //check you ASCII table, but i think that's right
if (isSpace(someChar))
your loop would count consecutive spaces, which probably wouldn't be an issue, but your logic would fail if there were multiple spaces between words and your count would be wrong
also, doing it your way, you want to use Spaces = in.get(); instead of in >> Spaces;