C++ – Read input file word by word


I will first off say that yes, this is a homework assignment, but my teacher is really not too clear on how to do things.

I'm asked to, in c++, Write a function that will pass words from a file one at a time. The function will calculate the word length and then print out TO SCREEN the word and its length on its own line.

The main will open your input file, read it word by word in a loop and then pass the word into your function for it to be printed.

I know how to open a file using fstream and all that, read it word by word, but not in a loop or a function by the void readfile () one. My problem here is putting everything together.

This is my program to open a file, get the length and display it in a parallel array

//declare parallel arrays

string words [MAXSIZE];

//open files
inputFile.open ("/Users/cathiedeane/Documents/CIS 22A/Lab 4/Lab 4 Part 2/lab4.txt");


while (!inputFile.eof())
    for(int i = 0; i < MAXSIZE; ++i)

        outputFile << words[i] << " " << endl;
        inputFile >> words[i];


for (int i= 0; i <= MAXSIZE; i++)

{   cout << words[i] << ":" << words[i].size()<< endl;
    outputFile << endl;

//close outputfile
return 0;

Best Solution

So basically your assignment is :

function read_word
  /* what you have to work on */

function read_file_word_by_word
  open file
  while not end_of_file
    word = read_word
    print word, word_length
  close file

To read a word, you need to define what it is. Usually it's a bunch of letters, delimited by other characters that are not letters (whitespace, commas, etc.).

You could read the file character by character and store them when they are letters until you encounter some other kind of character. What you have stored is a word, and you can get its length quite easily.

Tip: http://www.cplusplus.com/reference/istream/istream/get/ allows you to read a single character from a file.