I have to create a program which counts number of time the word "he" irrespective of case appears in a text file. I have written the program,it compiles but is showing wrong output if you type "he" in a sentence,if you just type it independently (without any other word/without sentence),any number of times,it shows the correct count.Please help.
#include<fstream>
#include<iostream>
#include<string.h>
#include<string>
usingnamespace std;
int main()
{
string content ;
int len,count_of_he = 0 ;
char ch, word[20];
ofstream f1("Akshat.txt",ios::out);
cout<<"\nEnter The Content for the file : " ;
getline(cin,content);
f1 << content ;
f1.close();
ifstream f2("Akshat.txt" , ios :: in);
while (f2>>word)
{
len = strlen(word);
if (!strcmp(word,"He") && (len == 2));
count_of_he++;
}
f2.close();
cout<<"\nThe number Of Time He Appears In The Sentence is = " << count_of_he ;
return 0;
}
@MikeyBoy i am trying to make the user input the data and then count number of time he appears is you look closely. With an already existing file,I am able to count the number of time he appears. The thing is i have to create a file,write the content in it and count in the same program.
@Thomas1965 what genius compiler is that,reporting an empty control statement? I use GNU/GCC it never does this,name please? though it didn't made any difference removing the ;
#include<fstream>
#include<iostream>
#include<string.h>
#include<string>
usingnamespace std;
int main()
{
constint EQUAL = 0;
string content;
int len, count_of_he = 0;
char ch, word[20];
ofstream f1("Akshat.txt", ios::out);
cout << "\nEnter The Content for the file : ";
getline(cin, content);
f1 << content;
f1.close();
ifstream f2("Akshat.txt", ios::in);
while (f2 >> word)
{
if (strcmp(word, "He") == EQUAL)
count_of_he++;
}
f2.close();
cout << "\nThe number Of Time He Appears In The Sentence is = "
<< count_of_he;
return 0;
}
If you want to count he or she you would need to convert word to lower case and use strstr instead of strcmp.
Try it first, if you can't get it to work I will post the full solution.
In Thomas1965's example, he simply replaced the 0 with the equivalent constant "EQUAL", which also is given the value 0. The logic is still the same as doing !strcmp(...).