40.6k views
0 votes
NO LINKS

Write a C++ program to accept a 5 digit integer and to validate the input based on the following rules.

Rules

1) The input number is divisible by 2. 2) The sum of the first two digits is less than last two digits. if the input number satisfies all the rules, the system prints valid and invalid, otherwise,

Example 1:

Enter a value: 11222

Output: Input number is valid

Example 2:

Enter a value: 1234

Output: Input number is invalid​

User Lavamantis
by
3.2k points

1 Answer

0 votes

Answer:

#include <iostream>

#include <string>

#include <regex>

using namespace std;

int main()

{

cout << "Enter a 5-digit number: ";

string number;

cin >> number;

bool valid = regex_search(number, regex("^\\d{4}[02468]$"));

if (valid) {

valid = stoi(number.substr(0, 1)) + stoi(number.substr(1, 1))

< stoi(number.substr(3, 1)) + stoi(number.substr(4, 1));

}

cout << number << (valid ? " is valid" : " is invalid");

}

Step-by-step explanation:

Regular expressions can do all of your checking except for the sum of digits check. The checks are i.m.o. easiest if you don't treat the input as a number, but as a string with digits in it.

The regex means:

^ start of string

\d{4} exactly 4 digits

[02468] one of 0, 2, 4, 6 or 8 (this is what makes it even)

$ end of string

User Dfjacobs
by
3.5k points