Menu: Difference between revisions

Content added Content deleted
(→‎{{header|C++}}: corrected; simplified)
Line 98: Line 98:


=={{header|C++}}==
=={{header|C++}}==
{{incorrect|C++|The <code>dataEntry</code> function should return a string, not void.}}
<lang cpp>#include <iostream>
<lang cpp>#include <iostream>
#include <boost/regex.hpp>
#include <boost/regex.hpp>
Line 104: Line 103:
#include <string>
#include <string>
using namespace std;
using namespace std;

void printMenu(const string *, int); //prints menu
void printMenu(const string *, int);
bool checkEntry(string, const string *, int); //checks whether entered data is in required range
//checks whether entered data is in required range
void dataEntry(const string *, int); //function that performs it all
bool checkEntry(string, const string *, int);

void dataEntry(const string *terms, int size) {
string dataEntry(string prompt, const string *terms, int size) {
if (size == 0) { //we return an empty string when we call the function with an empty list
if (size == 0) { //we return an empty string when we call the function with an empty list
cout << '\n';
return "";
return;
}
}
printMenu(terms, size);
cout << "Enter a number from 1 to " << size << " :\n";

string entry;
string entry;
cin >> entry;
do {

bool ok = checkEntry(entry, terms, size);
while (!ok) {
printMenu(terms, size);
printMenu(terms, size);
cout << "Enter a number from 1 to " << size << " :\n";
cout << prompt;
cin >> entry;
cin >> entry;
ok = checkEntry(entry, terms, size);
}
}
while( !checkEntry(entry, terms, size) );

int number = atoi(entry.c_str());
int number = atoi(entry.c_str());
cout << terms[number - 1] << '\n' ;
return terms[number - 1];
}
}

void printMenu(const string *terms, int num) {
void printMenu(const string *terms, int num) {
for (int i = 1 ; i < num + 1 ; i++) {
for (int i = 1 ; i < num + 1 ; i++) {
Line 137: Line 131:
}
}
}
}

bool checkEntry(string myEntry, const string *terms, int num) {
bool checkEntry(string myEntry, const string *terms, int num) {
boost::regex e("^\\d+$");
boost::regex e("^\\d+$");
Line 147: Line 141:
return true;
return true;
}
}

int main( ) {
int main( ) {
const string terms[ ] = { "fee fie" , "huff and puff" , "mirror mirror" , "tick tock" };
const string terms[ ] = { "fee fie" , "huff and puff" , "mirror mirror" , "tick tock" };
int size = sizeof terms / sizeof *terms;
int size = sizeof terms / sizeof *terms;
dataEntry(terms, size);
cout << "You chose: " << dataEntry("Which is from the three pigs: ", terms, size);
return 0;
return 0;
}</lang>
}</lang>