c++isspace

C++ Function does not seem to count the number of spaces in a text file


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.


Solution

  • 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