Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Reading in words from a text file, word by word or char by char

I've been googling around and reading through my book and trying to write out code to read through a text file and process words out of it, one by one, so i can put them in alphabetical order and keep a count of how many words where used and much a word was used. I can't seem to get my GetNextWord() function to work properly and it's driving me crazy.

I need to read the words in, one by one, and convert each letter to the lowercase if it is upper case. Which I know how to do that, and have done that successfully. It's just getting the word character by character and putting it into a string that is holding me up.

This is my most recent try at it: Any help would be amazing or a link to a tutorial over how to read from an input file word by word. (Word being alpha characters a-z and ' (don't) ended by whitespace, comma, period, ; , : , ect....

void GetNextWord()
{
    string word = "";
    char c;

    while(inFile.get(c))
    {
        while( c > 64 && c < 123 || c == 39)
        {
            if((isupper(c)))
            {
                c = (tolower(c));
            }
            word = word + c;
        }
        outFile << word;
    }
}
like image 239
Matt Swezey Avatar asked Dec 21 '22 23:12

Matt Swezey


1 Answers

You can read the file word by word by using the >> operator. For example, see this link: http://www.daniweb.com/forums/thread30942.html.

I excerpted their example here:

ifstream in ( "somefile" );
vector<string> words;
string word

if ( !in )
  return;

while ( in>> word )
  words.push_back ( word );
like image 177
Scott Stafford Avatar answered Jan 30 '23 07:01

Scott Stafford