Question : 18
Write a function in c++ named count_words() to read a file named “story.txt”. Count and print total words ending with ‘t or ‘T’ in the file
/*
count total words ending with ‘t’ or ‘T’ in the file
*/
Sol:
#include<iostream> #include<fstream> #include<stdlib.h> #include<string.h> using namespace std; void count_words() { ifstream pqr; char word[30]; int c=0; pqr.open("story.txt"); if (pqr.fail()) { cout<<"Unable to open the file"<<endl; exit(1); } while(!pqr.eof()) { pqr>>word; if(word[strlen(word)-1]=='t' || word[strlen(word)-1]=='T') { cout<<word<<endl; c++; } } pqr.close(); cout<<"total count "<<c<<endl; } int main() { /* clrscr(); */ count_words(); return(0); }
Question: 19
Write a function in c++ named count_words() to read a file named “story.txt”. Count and print total words with length 4 (ex: amit, male, tent etc.)
Sol:
#include<iostream> #include<fstream> #include<stdlib.h> #include<string.h> using namespace std; void count_words() { ifstream pqr; char word[30]; int c=0,len; pqr.open("story.txt"); if (pqr.fail()) { cout<<"Unable to open the file"<<endl; exit(1); } while(!pqr.eof()) { pqr>>word; len=strlen(word); if(len==4) { cout<<word<<endl; c++; } } pqr.close(); cout<<"total count "<<c<<endl; } int main() { /* clrscr(); */ count_words(); return(0); }
Question : 20
Write a function in C++ named “word_reverse()” to read the content of the file word by word and print reverse of each word.
example:
if file contains:
Hello How Are You
olleH woH erA uoY
Sol:
#include<iostream> #include<fstream> #include<stdlib.h> #include<string.h> using namespace std; void count_words() { ifstream pqr; char word[30]; pqr.open("story.txt"); if (pqr.fail()) { cout<<"Unable to open the file"<<endl; exit(1); } while(!pqr.eof()) { pqr>>word; cout<<strrev(word)<<" "; } pqr.close(); } int main() { /* clrscr(); */ count_words(); return(0); }