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

Dani AI

Generated

's suggestion to use getline for line counting is the right direction — it avoids most low-level newline pitfalls. The original getString in 's post exposes a few common issues that can leave lineCount unchanged; the likely culprits and fixes are below.

  • Reading a char before checking stream state: calling inFile.get(letter) and then inspecting letter can use a stale value if the read failed. Always test the stream state immediately after the read.
  • Platform line endings: if the file was opened in binary mode or came from a different OS, CR ('\r') and LF ('\n') can appear separately. std::getline normalizes this; low-level get() logic should check both '\n' and '\r'.
  • C character functions and signed char: isalpha, isalnum, tolower take an int which must be representable as unsigned char or EOF. Pass static_cast<unsigned char>(ch) to avoid undefined behavior.
  • Caller-side mistakes: verify the caller really passes the same lineCount (by reference) and does not shadow or reinitialize it.
  • Last-line edge case: code that only increments on '\n' will miss the final line if the file does not end with a newline. std::getline counts logical lines correctly.

A robust, simple pattern using getline plus a regex that matches alphabetic words (ASCII only) looks like this:

#include <fstream>
#include <iostream>
#include <regex>
#include <string>

int main()
{
    std::ifstream in("input.txt");
    if (!in) return 1;

    std::regex re("\\b[A-Za-z]+\\b"); // only letters
    std::string line;
    int lines = 0, words = 0;

    while (std::getline(in, line)) {
        ++lines;
        for (std::sregex_iterator it(line.begin(), line.end(), re), end; it != end; ++it)
            ++words;
    }

    std::cout << "lines: " << lines << ", words: " << words << '\n';
}

Notes: std::regex is straightforward but can be slower on large inputs and may not be available or fast on older compilers — in that case a tiny state machine that accumulates runs of alphabetic characters (committing a word when a non-alpha is seen) is the fastest fallback. Also remember the static_cast<unsigned char> rule whenever calling is*/to* C functions. Following these checks will resolve the common causes of lineCount staying zero while producing the alphabetic-only word counts that both and want.

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.