0

So i have this homework to do where the user inputs a number and how many number he wants to check and the computer tells him the numbers for which the first number is divisible.

The thing is that I wanted to do a little extra on the homework to block the program once a char or string is inputted, because else the program would crash

#include <iostream>
#include <stdlib.h>
#include <vector>

using namespace std;

int main() {
    unsigned int myNum, nTimes;
    bool Continue = true;
    char ContinueYN;
    vector<int> nDiv;


    while (Continue) {

        cout << "Insert a number.";
        cin >> myNum;
        cout << "How many numbers do you want to check?";
        cin >> nTimes;

        for (int I = 1; nTimes >= I; I++) {
            if (myNum % I == 0) {
                nDiv.push_back(I);
            }
        }

        cout << "The number is divisible for the following numbers: ";
        for (int i = 0; i < nDiv.size(); ++i) {
            cout << nDiv[i] << ' ';
        }
        
        cout << "\nPress any letter to continue or press n to stop\n";
        cin >> ContinueYN;
        ContinueYN = tolower(ContinueYN);

        if (ContinueYN == 'n') {
            Continue = false;
        }
        nDiv.clear();

        system("cls");
    }
    return 0;
}
  • 2
    Does this answer your question? [how do I validate user input as a double in C++?](https://stackoverflow.com/questions/3273993/how-do-i-validate-user-input-as-a-double-in-c) – Passerby Nov 14 '21 at 00:22
  • 1
    Check the state of the `istream` after input. If it's in a failed state, the extraction failed.Something like `if(std::cin >> variable) { success } else { if(std::cin.eof() return 1; else { std::cin.clear(); std::cin.ignore(std::numeric_limits::max()); std::cout << "bad input, try again\n"; }}` – Ted Lyngmo Nov 14 '21 at 00:36

0 Answers0