user2875331
user2875331

Reputation:

While loop causing an infinite loop but I can't figure out why

I am working on an assignment in C++ meant to teach us more about objects and OOP. Below is my code. The gist of it is, the user enters some input, and the program counts the number of vowels or consonants (chosen by the user), the total number of characters entered, and the total number of end-of-lines.

I am having three issues:

  1. The portion of code I've commented out is causing an infinite loop when left in. It causes the output from the countChars function to be printed infinitely, as well as the output asking the user if they would like to put in more input.
  2. The countChars function isn't counting EOL properly. I think it is most likely due to my unfamiliarity with the EOL. How do I signify it in my conditional statement? If I want to say, "increment if it has a value of '0'", I say, if (variable == 0). How do I tell C++ to increment if something is an EOL?
  3. countChars outputs random, negative values for the counts. I do notice the values changing depending on what I type (except EOL), but I am not sure why I am getting negative values. I'm not sure how to fix it beyond using an unsigned int and initializing the values.

Also, I foresee people telling me to use the getline function, but we had very specific instructions to use cin.get (we're supposed to learn a bit of everything, after all) so please, avoid a fix that uses getline.

Header file:

/*
+----------------------------------------+
|               CountChars               |
+----------------------------------------+
| -countVorC : Integer                   |
| -countEOL : Integer                    |
| -totalChars : Integer                  |
| -vowelCount : Boolean                  |
+----------------------------------------+
| <<constructor>>                        |
|   CountChars()                         |
| +inputChars() :                        |
| +vowelCheck(characterToCheck : Boolean)|
| +setVowelCount(VorC : Character)       |
| +getCountVorC() : Integer              |
| +getCountEOL() : Integer               |
| +getTotalChars() : Integer             |
| +getVowelCount() : Boolean             |
+----------------------------------------+
*/

using namespace std;

#ifndef COUNTCHARS_H
#define COUNTCHARS_H

class CountChars
{
private:
    unsigned int countVorC;
    unsigned int countEOL;
    unsigned int totalChars;
    bool vowelCount;
public:
    CountChars();
    void inputChars();
    bool vowelCheck(char characterToCheck);
    void setVowelCount(char VorC);
    int getCountVorC();
    int getCountEOL();
    int getTotalChars();
    bool getVowelCount();
};

#endif

Implementation file:

#include <iostream>
#include <iomanip>
#include <string>
#include <cctype>
#include <cstdio>
#include "CountChars.h"

using namespace std;

CountChars::CountChars()
{
    unsigned int countVorC = 0;
    unsigned int countEOL = 0;
    unsigned int totalChars = 0;
    bool vowelCount = false;
}

void CountChars::inputChars()
{
    int letter;

    while ((letter = cin.get()) != EOF && letter != EOF){
        if (vowelCount == true && (vowelCheck(letter) == true)) {
            countVorC++;
        }
        else if (vowelCount == false && (vowelCheck(letter) == false)) {
            countVorC++;
        }

        if (isalpha(letter)) {
            totalChars++;
        }

        if (letter == '\n') {
            countEOL++;
        }
    }
}

bool CountChars::vowelCheck(char characterToCheck)
{
    characterToCheck = toupper(characterToCheck);

    if ((isalpha(characterToCheck)) &&
       (characterToCheck == 'A' || characterToCheck == 'E' ||
       characterToCheck == 'I' || characterToCheck == 'O' ||
       characterToCheck == 'U')) {
       return true;
    }
    else {
        return false;
    }
}

void CountChars::setVowelCount(char VorC)
{
    VorC = toupper(VorC);

    if (VorC == 'V') {
        vowelCount = true;
    }
    else {
        vowelCount = false;
    }
}

int CountChars::getCountVorC()
{
    return countVorC;
}

int CountChars::getCountEOL()
{
    return countEOL;
}

int CountChars::getTotalChars()
{
    return totalChars;
}

bool CountChars::getVowelCount()
{
    return vowelCount;
}

Main:

#include <iostream>
#include <iomanip>
#include <string>
#include <cctype>
#include <cstdio>
#include "CountChars.h"

using namespace std;

void printCounts(CountChars);

int main()
{
    char VorC;
    char repeat = 'Y';
    CountChars charCounter;

    cout << "Welcome to the Character Counter Program!" << endl;
    cout << "\nWould you want to count vowels or consonants?" << endl;
    cout << "Type 'V' for vowels and 'C' for consonants: ";
    cin >> VorC;
    cout << endl;

    while (toupper(VorC) != 'V' && toupper(VorC) != 'C') {
        cout << "\nSorry, that was an invalid choice. Please try again: ";
        cin >> VorC;
        cout << endl;
    }


    do {
        cout << "You may being typing input below.\n" << endl;

        charCounter.setVowelCount(VorC);
        charCounter.inputChars();
        cin.clear();
        printCounts(charCounter);

        cout << "\nWould you like to enter new input?" << endl;
        cout << "Type 'Y' for yes or 'N' for no: ";
        cin >> repeat;
        cout << endl;

        while (toupper(repeat) != 'Y' && toupper(repeat) != 'N') {
                cout << "\nSorry, that was an invalid choice. Please try again: ";
                cin >> repeat;
                cout << endl;
        }

    } while (toupper(repeat) == 'Y');

    cout << "\nThank you for using the Character Counter Program!\n" << endl;

    system("pause");
    return 0;
}

void printCounts(CountChars charCounter)
{
cout << "\nTotal characters: " << charCounter.getTotalChars() << endl;

        if (charCounter.getVowelCount() == true) {
            cout << "Total vowels: " << charCounter.getCountVorC() << endl;
        }
        else {
            cout << "Total consonants: " << charCounter.getCountVorC() << endl;
        }

        cout << "Total end-of-lines: " << charCounter.getCountEOL() << endl;
}

Upvotes: 0

Views: 3836

Answers (1)

Jonathan Leffler
Jonathan Leffler

Reputation: 755064

cin.get() returns an int

You have:

char letter;

while ((letter = cin.get()) != EOF)

If the plain char is an unsigned type, as it is on some machines, then this will never evaluate to true because the value -1 (the normal value for EOF) is assigned to an (unsigned) char, it is mapped to 0xFF, and when 0xFF is compared with an int like EOF (that is still -1), the answer is false, so the loop continues.

The fix for this is to use int letter instead of char letter. (Note that there's a different problem with the code as written if char is a signed type; then, the character with code 0xFF — often ÿ, y umlaut, U+00FF, LATIN SMALL LETTER Y WITH DIAERESIS — is misinterpreted as EOF. The fix is the same; use int letter;).

I suspect, though, that this is only part of the trouble.


EOF is not EOL

In the same function, you also have:

    if (letter == EOF) {
        countEOL++;
    }

You know that letter is not EOF (because the loop checked that). Also, you wanted to count EOL, not EOF (there is only one EOF per file, though if you keep attempting read beyond EOF, you will get EOF returned repeatedly). You probably need:

    if (letter == '\n') {
        countEOL++;
    }

or maybe you want to define EOL and compare to that:

    const int EOL = '\n';
    if (letter == EOL) {
        countEOL++;
    }

cin leaves the newline in the input

In the code:

cout << "Type 'V' for vowels and 'C' for consonants: ";
cin >> char(VorC);
cout << endl;

while (toupper(VorC) != 'V' && toupper(VorC) != 'C') {
    cout << "\nSorry, that was an invalid choice. Please try again: ";
    cin >> char(VorC);
    cout << endl;
}

The first cin operation leaves the newline in the input stream. If the use typed 'Y', say, then the next cin operation (inside the loop) will read the newline, and since the newline is neither 'V' nor 'C', it will complain again (but would then wait for more input).

Add #include <limits> and use:

cin.ignore(numeric_limits<streamsize>::max(), '\n');

to read past the newline.

Again, this isn't the whole problem.


Can't continue reading cin after EOF

And the final installment, I think…

Your commented out code is:

/*do {
    cout << "You may being typing input below.\n" << endl;*/

    charCounter.setVowelCount(VorC);
    charCounter.inputChars();

    /*cout << "Would you like to enter new input?";
    cout << "Type 'Y' for yes or 'N' for no: " << endl;
    cin >> char(repeat);
    cout << endl;
        while (toupper(repeat) != 'Y' && toupper(repeat) != 'N') {
            cout << "\nSorry, that was an invalid choice. Please try again: ";
            cin >> char(repeat);
            cout << endl;
        }
} while (toupper(repeat) == 'Y');*/

Note that the call to charCounter.inputChars() doesn't stop until cin has reach EOF. There isn't any more input at that point, so the cin in the loop (that is commented out) will fail every time, never generating a 'Y'. You need to clear the errors on cin so that you can enter more data, such as the answer to the 'more input' question.

I wonder if you've confused EOL and EOF in the reading code. Maybe you intended to read only to the end of a line rather than to the end of the file. Then your loop condition (the one I mentioned first) should be:

int letter;

while ((letter = cin.get()) != EOF && letter != '\n')  // Or EOL if you define EOL as before

You should always be prepared for any of the input operations to return EOF when you didn't really expect it, as here.


Ever the optimist! The previous installment was not the final one.

The constructor doesn't construct

I still have the issue of junk being printed, though. For example, it says Total characters: -85899345.

I tried to compile your code:

$ g++ -O3 -g -std=c++11 -Wall -Wextra -Werror -c CountChars.cpp
CountChars.cpp: In constructor ‘CountChars::CountChars()’:
CountChars.cpp:13:18: error: unused variable ‘countVorC’ [-Werror=unused-variable]
     unsigned int countVorC = 0;
                  ^
CountChars.cpp:14:18: error: unused variable ‘countEOL’ [-Werror=unused-variable]
     unsigned int countEOL = 0;
                  ^
CountChars.cpp:15:18: error: unused variable ‘totalChars’ [-Werror=unused-variable]
     unsigned int totalChars = 0;
                  ^
CountChars.cpp:16:10: error: unused variable ‘vowelCount’ [-Werror=unused-variable]
     bool vowelCount = false;
          ^
cc1plus: all warnings being treated as errors
$

You've declared local variables in your constructor that hide the class members, so your constructor doesn't actually usefully construct. The junk numbers are because you start with junk.

cin >> char(VorC) does not compile everywhere

Similarly, when I tried to compile Main.cpp, I got errors starting:

$ g++ -O3 -g -std=c++11 -Wall -Wextra -Werror -c Main.cpp
Main.cpp: In function ‘int main()’:
Main.cpp:18:9: error: ambiguous overload for ‘operator>>’ (operand types are ‘std::istream {aka std::basic_istream<char>}’ and ‘char’)
     cin >> char(VorC);
         ^
Main.cpp:18:9: note: candidates are:
In file included from /usr/gcc/v4.9.1/include/c++/4.9.1/iostream:40:0,
                 from Main.cpp:1:
/usr/gcc/v4.9.1/include/c++/4.9.1/istream:120:7: note: std::basic_istream<_CharT, _Traits>::__istream_type& std::basic_istream<_CharT, _Traits>::operator>>(std::basic_istream<_CharT, _Traits>::__istream_type& (*)(std::basic_istream<_CharT, _Traits>::__istream_type&)) [with _CharT = char; _Traits = std::char_traits<char>; std::basic_istream<_CharT, _Traits>::__istream_type = std::basic_istream<char>] <near match>
       operator>>(__istream_type& (*__pf)(__istream_type&))
       ^
/usr/gcc/v4.9.1/include/c++/4.9.1/istream:120:7: note:   no known conversion for argument 1 from ‘char’ to ‘std::basic_istream<char>::__istream_type& (*)(std::basic_istream<char>::__istream_type&) {aka std::basic_istream<char>& (*)(std::basic_istream<char>&)}’
/usr/gcc/v4.9.1/include/c++/4.9.1/istream:124:7: note: std::basic_istream<_CharT, _Traits>::__istream_type& std::basic_istream<_CharT, _Traits>::operator>>(std::basic_istream<_CharT, _Traits>::__ios_type& (*)(std::basic_istream<_CharT, _Traits>::__ios_type&)) [with _CharT = char; _Traits = std::char_traits<char>; std::basic_istream<_CharT, _Traits>::__istream_type = std::basic_istream<char>; std::basic_istream<_CharT, _Traits>::__ios_type = std::basic_ios<char>] <near match>
       operator>>(__ios_type& (*__pf)(__ios_type&))
       ^
…
$

The problem here is the:

cin >> char(VorC);

You really don't want the cast there:

cin >> VorC;

You arguably should check that the input works:

if (!(cin >> VorC)) …process EOF or error…

This same problem afflicts the cin >> char(repeat);, of course.

I don't know why it compiled for you; it should not have done so. With that fixed, it sort of works. I ran into the 'newline still in input' so the inputChars() function got zero characters before EOL, etc. Now it is up to you to deal with that.

Upvotes: 3

Related Questions