Hi,
Im trying to write a program that I put 2 input files with some words in each one ,convert them into the array, then my program should decide how many times each words used in those 2 files.output should be like this:
Output:
am 2
because 2
don’t 1
happy 2
i 4
sing 2
I just could write this much and i m not sure even this is correct or not!
Hi,
my program should decide how many times each words used in those 2 files ... i m not sure even this is correct or not!
1 2 3 4 5 6
int count = 0;
std::string word;
while (fin >> word) {
words[count] = word;
count++;
}
I don’t think the logic is correct.
What that loop does, is storing all words into an array. That represents a single piece of information, while you need at least two pieces of information, i.e. the word and its frequency.
Since you use std:.strings, perhaps you want to use a std::map to achieve that purpose. If you don’t feel confident with std::maps, you could use two std::vectors (or even two C-style arrays) which work together to store each word and its frequency at the same index.
For example, you could add another loop inside the above loop, which compare the latest read word with those already stored inside the array. If the comparison is positive, instead of adding that word, it increases its frequency.
Once you’ve correctly read the data, you can proceed to the next step, their output.
#include <fstream>
#include <iostream>
#include <string>
int main()
{
std::string words[100];
int words_freq[100];
// initialise all 'ints' inside 'words_freq' to 0
std::ifstream fin("words.txt");
// check if 'fin' has been correctly opened
std::string word;
for (int count = 0; fin >> word; ++count) {
if(count) {
// create a variable to store a "word already found" state
// initialise the above variable to false
// start a loop with incresaing counter up to 99 {
// check if "words[counter]" is equal to "word" - if so {
// "words_freq[counter]" should be increased by one
// set the state "word already found"
// skip the rest of the loop
// }
// } end loop
}
if( ! "word already found" ) {
words[count] = word;
}
}
return 0;
}