0

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;
	}
}
2
Contributors
3
Replies
4
Views
9 Years
Discussion Span
Last Post by Ancient Dragon
0

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;
   }
}
0

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

0

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!
   }
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.