In: Computer Science
C++. Set hasDigit to true if the 3-character passCode contains a digit.
#include
#include
#include
using namespace std;
int main() {
bool hasDigit;
string passCode;
hasDigit = false;
cin >> passCode;
/* Your solution goes here */
if (hasDigit) {
cout << "Has a digit." << endl;
}
else {
cout << "Has no digit." << endl;
}
return 0;
// Declare required header file
// iostream is used for input output
#include
// string is used to use string type
// character
#include
// This header file use here for
// using the isdigit() function
// to check digits is exist or not
#include
// Namespace std for cin cout
using
namespace
std;
// Create a main function of the
// program
int
main()
{
// Declare hadDigit is a Boolean
// variable
bool
hasDigit;
// Declare passCode is a string character
string passCode;
// Initially hasDigit Declare
// false statement
hasDigit =
false
;
// Prompt the passcode from console
cin >> passCode;
/* Your solution goes here */
// Declare the position of 3 digits
// passCode.at(hold the input position value)
// It means passCode.at() find out the value form that position.
// Assign the input value to digit1 from index 0
int
digit1 = passCode.at(0);
// Assign the input value to digit2 from index 1
int
digit2 = passCode.at(1);
// Assign the input value to digit3 from index 2
int
digit3 = passCode.at(2);
// When anyone digits(digit1, digit2,digit3) contains a digit
if
(
isdigit
(digit1) ||
isdigit
(digit2) ||
isdigit
(digit3))
{
// Set hasDigit to true
hasDigit =
true
;
}
// When hasDigit contains true
if
(hasDigit) {
// Display has a digit
cout <<
"Has a digit."
<< endl;
}
// Otherwise it has no digit
else
{
cout <<
"Has no digit."
<< endl;
}
return
0;
}
The following information has been provided for the question above:
Screen shot of C++ code:
Output:
Text format code:
// Header files section
#include <iostream>
#include <cctype>
#include <string>
using namespace std;
//Program begins with a main function
int main()
{
//Declare variable
string passCode;
//Initialize the variables
bool hasDigit = false;
passCode = "abc";
//Set hasDigit to true if the 3-character
//passCode contains a digit.
if (isdigit(passCode.at(0)) || isdigit(passCode.at(1))
|| isdigit(passCode.at(2)))
{
hasDigit = true;
}
if (hasDigit)
{
cout << "Has a digit." << endl;
}
else
{
cout << "Has no digit." << endl;
}
return 0;
}