0

I'm trying to count different types of characters in a text file "nums.txt" I used a while loop with an ifstream object to check each character individually. Currently, all of my character types (punctuation, digits, uppercases, etc.) correctly display their corresponding number except for the blank space character ' '.

This is what I have in the loop currently:

while (inFile >> inChar){
    if (isupper(inChar))
       upperCount++;
    else if (islower(inChar))
       lowerCount++;

     // the rest of the char types

     else if (isspace(inChar))
        spaceCount++;
}

Whenever I run the program, the display shows 0 for number of spaces and I have no idea why. Thanks.

Teaaaaaaa
  • 3
  • 1
  • 3
    `inFile >> inChar` will skip all whitespace unless you tell it not to, something that is not done in the snippet of code given. [See documentation](https://en.cppreference.com/w/cpp/io/basic_istream/operator_gtgt2) for more on this and how to get around the problem. – user4581301 Mar 12 '20 at 01:37
  • 2
    Instead of `inFile >> inChar` do `inFile.get(inChar)`. – David G Mar 12 '20 at 01:44
  • No worries, but if the loop is now `while (true)`, how does the loop exit? – user4581301 Mar 12 '20 at 02:04
  • I included `if (inFile.eof()) { break; }` to stop it. – Teaaaaaaa Mar 13 '20 at 02:23

1 Answers1

1

If you don't want your istream to skip whitespace (spaces, tabs, and newlines are all considered whitespace), then you need to tell it to explicitly not skip whitespace.

You can do this by passing the stream manipulator std::noskipws to the stream before performing formatted input:

std::cin >> std::noskipws;

Be sure to reset it to normal behavior when you're finished, or the >> operator won't work as expected.

std::cin >> std::skipws;

https://en.cppreference.com/w/cpp/io/manip/skipws

JohnFilleau
  • 4,045
  • 1
  • 15
  • 22