C++ limit input to only be integars so letters aren't valid

Viewed 230

See code below. It works fine for numbers but if I enter a letter (eg 'a'), it will output 'first number 0 is divisible by second number, 6487956' without asking for input of second number.

#include<iostream>
using namespace std;

int main()
{
    int first, second;

    cout << "Please enter your first number (must be an integer) : "  ;
    cin >> first  ;
    cout << "Please enter your second number (must be an integer) : ";
    cin >> second ;

    if (first % second == 0)
        cout << "The first number, " << first << ", is divisible by the second number, "     << second << ".";
        else
        cout << "The first number, " << first << ", is not divisible by the second number, " << second << ".";
return 0;
}
1 Answers

Here is an example which will not accept if input has any characters. Function to check if string has only numbers.

#include <iostream>
#include <string>
#include <algorithm>

bool is_digits(const std::string& str)
{
    return std::all_of(str.begin(), str.end(), std::isdigit);
}

void get_number(std::string& number, const char* string) {
    std::cout << string;
    std::getline(std::cin, number);
    if (!is_digits(number)) {
        get_number(number, string);
    }
}

int main()
{
    std::string first, second;
    get_number(first, "Please enter your first number (must be an integer) : ");
    get_number(second, "Please enter your second number (must be an integer) : ");

    if (std::stoi(first) % std::stoi(second) == 0)
        std::cout << "The first number, " << first << ", is divisible by the second number, " << second << ".";
    else
        std::cout << "The first number, " << first << ", is not divisible by the second number, " << second << ".";
    return 0;
}

or

#include <iostream>
#include <string>
#include <algorithm>

bool is_digits(const std::string& str)
{
    return std::all_of(str.begin(), str.end(), std::isdigit);
}

int get_number(const char* string) {
    static std::string number;
    std::cout << string;
    std::getline(std::cin, number);
    if (!is_digits(number)) {
        get_number(string);
    }
    return std::stoi(number);
}

int main()
{
    int first = get_number("Please enter your first number (must be an integer) : ");
    int second = get_number("Please enter your second number (must be an integer) : ");

    if (first % second == 0)
        std::cout << "The first number, " << first << ", is divisible by the second number, " << second << ".";
    else
        std::cout << "The first number, " << first << ", is not divisible by the second number, " << second << ".";
    return 0;
}
Related