Hello everyone,
I decided to find out how many words in the english language contain no vowels, so I downloaded a list of almost all the words in the english language and set to work writing a program. What I want it to do is take each word (each new line), analyse it and look for vowels, then use cout<< to output it if there is none in it. So far I have this:
#include <iostream>
#include <fstream>
#include <string>
usingnamespace std;
int main () {
string line;
bool vowel;
ofstream myfile;
myfile.open ("brit.txt");
if (myfile.is_open())
{
while ( myfile.good() )
{
getline (myfile,line);
int i=0;
while(line[i]){
if(line[i]='a'||'e'||'i'||'o'||'u'){
vowel=true;
break;
}
i++;
}
if(!vowel)cout<<line;
}
myfile.close();
}
else cout << "Unable to open file";
system("PAUSE);
return 0;
}
This does not compile or do what I want.It says there is no matching function for getline(). How can I get it to take one line at a time, analyse it, then move on to the next one?
OK, I've changed the ofstream to an ifstream, and the code compiled, but it didn't output any words. I've checked, the word list does include at least one word without any vowels. I also added a message to show when it'd finished searching. It came to the end of the search without sending out any words with no vowels, so it's still not working...
After having a look, I think I know what the newest problem is. I'm assuming the getline() function will get the first line, then stop, in which case only the first line of the file will be read. Is that the problem, and how can it be fixed?
You should put this line within the while (myfile.good()) loop:
if(!vowel)cout<<line;
because, where it is now, it only outputs the last line read if a vowel was encountered at some point. You should also set vowel to false at the beginning of the same loop.
A big issue is with your if statement:
if(line[i]='a'||'e'||'i'||'o'||'u')
This will always be true because it will evaluate line[i]='a' (note this is assignment, not comparison) first, this will evaluate to 'a' as an expression which is non-zero which is true. Note that all the other expressions in this statement evaluate to true as well.
because, depending on the file, the while ( myfile.good() ) will create an extra iteration if the EOF character did not get reached from the "last" read. getline doesn't return a bool but it will still work in this case.
If none of this fixes your issue, please post your new code so we can have a look.
That works, thankyou! What I need to remember for next time is to set the variables to the right value (vowel=false;), check I'm using a comparison, not an assignment (==, not =), and to look in detail at the library (ifstream, not ofstream). There's a surprising amount of words withoult vowels in - it came up with a long list!