Hey Guys,
So, I am writing a program that reads in from a file, and prints the word and counts the number of lines in the document. Here is the function that is supposed to do the work. Every time I run it lineCount is always 0.

string getString(ifstream& inFile, int &lineCount)
{
	char letter;
	string letters = "";  

	inFile.get(letter);
	
	if(letter == '\n')
		lineCount++;
	while(inFile && !isalnum(letter))
	{
		if(letter == '\n')
		{
				lineCount++;
		}
		
		inFile.get(letter);
	}

	if (!inFile)
		return letters;
	else
	{
		do
		{
			letter = tolower(letter);
			letters = letters + letter;
			inFile.get(letter);
		}while (isalnum(letter) && inFile);

		return letters;
	}
}

Recommended Answers

All 3 Replies

just use getlin() to get each line

#include <sstream>
//
<snip>

std::string line;
int lines = 0;
int words = 0;
while( getline( inFile, line) )
{
   lines = lines + 1;
   // now split line into words
   stringstream str(line);
   string word;
   while( str >> word)
   {
      words = words + 1;
   }
}

ok, line count should work. But, words in our program aren't supposed to include non alphabetic characters. How would I go about that?

loop though the word and check if it contains any non-alphabetic character. The mactor isalpha() should be handy for that

for(int i = 0; i < word.size(); i++)
{
   if( !isalpha(word[i])
   {
       // oops!
   }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.