/*
* @topic T00250 string input and validation
* @brief <br />using hexadecimal and decimal output format<br /><br />
*/
/*
This is our first prototype for homework Assignment
that deals with binary to hex conversion.
The program below can input and validate user input.
The work is done in separate functions.
The main() function makes calls to delegate tasks
to other functions.
The program also shows how you can display numbers
in hexadecimal or decimal format.
*/
#include <string>
#include <iostream>
// function to validate user input
bool validate_user_input( std::string str )
{
// make sure that str is made of only '0' and '1' characters
int idx = 0;
int size = str.length();
for ( ; idx < size; ++idx ) {
// for every character in the string
char ch = str[ idx ]; // get character
if ( ch == '0' ) { // if zero,
continue; // go on
} else if ( ch == '1' ) { // if one,
continue; // go on
} else { // if anything else,
return false; // validation fails
}
}//for
// no characters other than zero or one were found,
return true; // validation succeeds
}
// function to display prompt and get user input
std::string get_user_input( std::string prompt )
{
std::cout << prompt; // display prompt
std::string str; // create string
std::cin >> str; // get user input
return str; // return user input
}
// program begins here:
int main()
{
std::string str_bin_num;
// Until the user enters a binary number correctly,
// keep asking for input:
for(;;) {
// forever -- endless loop
// get user input:
str_bin_num = get_user_input( "Enter a bin #>" );
// validate user input:
if ( validate_user_input( str_bin_num ) ) {
// everything is okay,
break; // exit the loop
} else {
std::cout << "bad input! please retry\n";
}
}//for
std::cout << "You typed: " << str_bin_num << '\n';
// The rest of this demo shows how to
int value = 0x5A7BF; // specify hex number in your program
std::cout << std::hex << value << '\n'; // display the hex number
std::cout << std::dec << value << '\n'; // display the decimal number
return 0;
}