my question is this... i was givin a paragraph and was told to write a program that will read from a txt file and print out how many words are of a certain length... in example, if the file said, "This program will count the number of words in a file." then output is supposed to say
int main()
{
fstream textfile; //create object
textfile.open("thetextfilesname.txt"); //create and open file for manipulation
//the code to do the required tasks
textfile.close(); //close and update file
return 0;
}
You'll probably need flags and such but that link should help with that. As for number of words...
If the lines are simple English you could just count each whitespace (in a loop) and increment a counter every time you hit one. Because of course in English (and languages in general) words are separated with a space meaning that each space has a word before it.
The word length would be a bit trickier though. Every time you hit a non-whitespace character you could start a function that would count each character until a whitespace occurs.
Something tells me there is an easier solution, but at the moment it isn't coming to me.
i have the fstream down... what we were told to do first was make the file read the file and then write the whole thing onto another file, and i did that, then she told us to build off of that and make it read from the file and then write the number of words for the amount of letters in each word, and thats where im messing up... i cant figure out how to write the code so that it prints out the number of letters for the words.
Here is a small piece of code that with slight modifications could count the words in a line:
1 2 3 4 5 6 7 8
getline(textile, line); //put one line in the string container called line
for (i = 0; i < line.length(); i++) //as long as line has more characters
{
if (line[i] == '') //if there is a whitespace
{
words++; //another word!
}
}
Here is a program that prints the word count by word length for a paragraph read from the console. You may modify this code to read the paragraph from a file instead.
I am on the very chapter in my book that covers that topic. Based on what I understand from that chapter (I am still learning C++), your program will have 3 parts.
1) Create a string vector for the words in your text. Use istringstream() and getline() to read the words from your text into the vector.
2) Use vector.size() and string.length() to determine the total number of words read into the vector and the number of letters in each word. Create an int vector for storing the number of words of each length. If you are clever, you will use the vector index as the word length: word length = index + 1.
3) Print out the pairs of word length and number of words.
This is what I would do based on my current knowledge and understanding. A C++ veteran will give you better suggestions.