I'm trying to solve a problem and i can't figure out how to do it. The problem says that given an input file which has on the first line a number k and on the next lines some words, K is the minimum number of vowels that a word needs to have to be printed in the console.
Example:
Input: test.in
cars
are...great and awesome
Output:
If k is 2 the result should be:
are
great
awesome
And also it should not take into account spaces or other characters like .,!,? and so on.
What i have so far:
int main(){
ifstream fin("dataTest.in");
char s[250];
int k;
fin>>k;
int nrVowels=0;
while(fin>>s) {
int n = strlen(s);
for(int i=0; i < n; i++)
{
if (s[i] == 'a' || s[i] == 'e' || s[i] == 'o' || s[i] == 'i' || s[i] == 'u'){
nrVowels++;
if(nrVowels == k){
cout<<"Here i guess i should print the word?";
}
}
}
}
}
As you can see from the code my problem is that i'm not really sure how i should print the word and how would i know where the word is ending because i don't want to print only a part of the word. Do you guys have any ideas on how i should do this?
Your requirements state that "K is the minimum number of vowels that a word needs to have to be printed in the console", which would translate to the greater or equal condition
However, your code prints the word as soon as
k
vowels are found, so you can keep your condition as is. But you should break the inner loop once the required count was reached.Also, as it was commented already, you need to reset the
nrVowels
counter for each word that you inspect. Better yet: makenrVowels
a local scope variable within the body of your while-loop.Some hints regarding your code that are not strictly necessary to solve the problem:
std::string
instead of char arrays.code:
First fix obvious problems
You have
in combination with
is a potential buffer overrun. changing s to
now you get
for free.
is rather long it would be better to say
by making (as Kaldrr proposed)
This gives
But there is still the problem of each word is tested instead of each string.
What we want is
Thanks for answering! I've modified my code with this based on your help:
It kind of works now but i need also to separate words that have.,? and so on. How should that be done?