56.6k views
0 votes
Write a complete C++ program that does the following:

Prompts the user for a positive integer with between two and five digits
Validate the input; force the user to enter a number that matches the input requirements
Prints the first digit of the input and the last digit of the input.

1 Answer

3 votes

Final answer:

The C++ program prompts the user for a 2-5 digit positive integer, validates the input, and prints the first and last digits using a do-while loop and string indexing.

Step-by-step explanation:

To write a complete C++ program that prompts the user for a positive integer between two and five digits, validates the input, and prints the first and last digit, you can use the following approach:

#include <iostream>
#include <string>

int main() {
int num;
std::string input;

do {
std::cout << "Please enter a positive integer with between two and five digits: ";
std::cin >> input;
num = std::stoi(input);
} while (input.length() < 2 || input.length() > 5 || num <= 0);

std::cout << "First digit: " << input[0] << '\\';
std::cout << "Last digit: " << input[input.length() - 1] << '\\';

return 0;
}

This program uses a do-while loop to continually ask the user for a number until the correct input is received. Then it prints out the first and last digit of the given number using string indexing.

User Boyan
by
9.4k points