vendredi 2 mars 2018

How do I successfully clear streams?

I sincerely hope my question is on point. If not, it'll be edited.

I'm writing a program that needs to find abundant, deficient and perfect numbers - according to Greek numerology. What represents an issue here is ensuring that only natural numbers are inserted; more specifically making sure that there are no letters inserted. I tried checking if stream was "broken", if true, print appropriate message. It works, but only once, and I can't figure out why. Here's the code.

 #include <iostream>
 int main ()
{
double n(0);
int sum(0);
int i(0);

std::cout << "Enter a natural number or 0 for exit: ";
std::cin >> n;

int n1 = n;
do {
    for(i = 1; i < n1; i++) {
        if(n1 % i == 0) {
            sum+=i;
        }
    }
    if(!std::cin) {
        std::cout << "Not a natural number!" << std::endl;
        std::cout << "Enter a natural number or 0 for exit: ";
    }
    else if(n != int(n)) {
        std::cout << "Not a natural number!" << std::endl;
        std::cout << "Enter a natural number or 0 for exit: ";
    }
    else if(n1 < 0) {
        std::cout << "Not a natural number!" << std::endl;
        std::cout << "Enter a natural number or 0 for exit: ";
    }
    else if(suma < n1) {
        std::cout << "Number " << n << " is deficient!" << std::endl;
        std::cout << "Enter a natural number or 0 for exit: ";
    }
    else if(suma > n1) {
        std::cout << "Number " << n << " is abudant!" << std::endl;
        std::cout << "Enter a natural number or 0 for exit: ";
    }
    else if(suma == n1) {
        std::cout << "Number " << n << " is perfect!" << std::endl;
        std::cout << "Enter a natural number or 0 for exit: ";
    }
    suma = 0;
    std::cin.clear();
    std::cin.ignore(1000, '\n');
    std::cin >> n;
    n1 = int(n);
} while(n != 0);
std::cout << "Goodbye!";

return 0;

}

Aucun commentaire:

Enregistrer un commentaire