I'm trying to figure out the word frequency of a user inserted string.
I've tried doing it via getline of the struct array and via the getline of the string word but neither either the former crashes or the latter just prints out the whole string.
#include "stdafx.h"
#include <iostream>
#include <string>
#define MAX_WORDS 200
usingnamespace std;
struct Word{
string word;
int cnt;
}sWord;
class Dict{
public:
int doesAll(int index);
private:
Word allwords[MAX_WORDS];
int num;
int search;
}dict;
int main(){
dict.doesAll(0);
return 0;
}
int Dict::doesAll(int index){
Word structArray[MAX_WORDS];
index = 0;
unsignedint i = 0;
cout<<"Please enter your sentences; you can enter"<<endl<<" CTRL+Z in a new line to finish the input: "<<endl;
cout<<endl;
getline (cin,sWord.word);
int length = sWord.word.length();
for(int k=0;k<length;k++)
structArray[k].word = sWord.word;
//think the issue is in the above;
// Skip over spaces at the beginning of the word
while(isspace(sWord.word .at(i)))
i++;
for(; i < sWord.word.length(); i++){
if(isspace(sWord.word.at(i))){
index++;
// Skip over duplicate spaces & if a NULL character is found, we're at the end of the string
while(isspace(sWord.word.at(i++)))
if(sWord.word.at(i) == '\0')
index--;
}
}
// The number of words = the number of spaces + 1
sWord.cnt=index+1;
cout<<endl<<"Total number of words: "<< sWord.cnt<<endl;
sWord.cnt = dict.num;
string t1, t2;
//string words[MAX_WORDS] = sWord.word;
int num[MAX_WORDS] = {0};
//does frequency count
for(int j = 0; j < 5; j++)
{
t1 = structArray[j].word;
for(int i = 0; i < 5; i++)
if(t1 == structArray[i].word)
num[j]++;
}
for(int i = 0; i < 5; i++)
cout << structArray [i].word << " " << num[i] << endl;
return sWord.cnt;
}
I'm a bit behind in class and not sure how to handle the array of structs that my teacher wants me to use.
I know Code is disorganized atm, I'll tidy it up once I get things working.
std::string line;
std::getline(std::cin, line);
std::ostringstream temp(line);
std::string word;
while(temp >> word)
{
for(auto& letter: word)
letter = tolower(letter);
/*Now you have single word here in all lowercase. Do whatever you need here*/
}
Oops. I mistyped. 'o' and 'i' is somewhat close... Yes use istringstream. And what about you sing struct array? My code doesn't prevent you to using it. What I did is give you a single word in string variable. You can place it in your array, you can seach for it in array, you can do pretty much everything...