Hi guys, my teacher asked for a program to count all words that contain 3,4,5,6 letters in them . he asked to use nested sentinel-controled loops and filein.get(inchar)
and am completely clueless on how to code this.
the out put should be :
3 letter words : (num)
4 letter words : (num)
5 letter words : (num)
6 letter words : (num)
can u help me out plz?
Why would you be given a task that you have no idea how to go about solving?
Have you done simpler file i/o tasks yet?
The program below simply prints out the letters or a new line for each space character.
Does it give you a clue how you might count the length of each word?
/* Problem: a program to count all words that contain 3,4,5,6 letters in them.
use nested sentinel-controlled loops and infile.get(inchar).
the out put should be :
3 letter words : (num)
4 letter words : (num)
5 letter words : (num)
6 letter words : (num)
*/
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
usingnamespace std;
ifstream infile;
ofstream outfile;
int main()
{
char inchar;
// outfile.open("NUMWORDS.txt");
infile.open("QUOTES.txt");
while (infile)
{
//need to do nested loops to count the words with 3,4,5,6 letters
infile.get(inchar);
if (inchar == ' ')
cout << endl;
else
cout << inchar;
}
// close file
infile.close();
}
Ok, that's a start. It's a little bit tricky reading strings from a file. So what we tend to do is read the whole line, then use stream stuff to read the individual words from that line.
I'll write that code for you. You'll need to check the length of the strings and do stuff with it. If you're stuck on that, once you make an effort, someone will help with that part.
A few rules to remember.
1. Make variables (objects) as local as possible; that way you end up avoiding globals.
2. Declare variables where they are used. Forget declaring variables at the top of the function or file or whatever.
3. The file objects provide streams. Think streams of data, not files that you open, close, check for end of file and so on.
#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
int main()
{
std::ifstream infile("QUOTES.txt");
// read full line from file
std::string line;
while (std::getline(infile, line))
{
std::istringstream iss(line);
// read words from line
std::string word;
while (iss >> word)
{
// print the words and their length
std::cout << word.size() << ": " << word << std::endl;
}
}
}