How can you say you're sticking with C when you're using C++ streams? Everyone is entitled to their opinion, of course, but your remarks have no real technical validity. C++ will almost always result in more robust code with fewer errors, with little, if any, performance degradation. It represents a mature advance made possible by technological gains.
Here are versions for C and C++.
C++
Code:
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int menu ();
int main ()
{
int choice = 0;
while (choice != 3)
{
choice = menu ();
cout << "Your choice was " << choice << endl;
}
return 0;
}
int menu ()
{
int choice = 0;
while (1)
{
cout << "Enter your selection (1, 2, 3 to exit): ";
cin >> choice;
if (!cin.good ()) choice = 0;
if ((choice < 1) || (choice > 3))
cout << "Your selection was invalid. Try again.\n" << endl;
else return choice;
cin.sync ();
cin.clear ();
}
return choice;
}
C
Code:
#include <stdio.h>
int menu ();
int main (int argc, char *argv [])
{
int choice = 0;
while (choice != 3)
{
choice = menu ();
printf ("Your choice was %d\n", choice);
}
return 0;
}
int menu ()
{
int choice = 0;
while (1)
{
printf ("Enter your selection (1, 2, 3 to exit): ");
if (scanf ("%d", &choice) != 1) choice = 0;
if ((choice < 1) || (choice > 3))
puts ("Your selection was invalid. Try again.\n\n");
else return choice;
rewind (stdin);
}
return choice;
}
Quote:
Originally Posted by Output
E:\Documents and Settings\David\My Documents\Visual Studio 2005\Projects\Menu\de
bug>menu
Enter your selection (1, 2, 3 to exit): aaa
Your selection was invalid. Try again.
Enter your selection (1, 2, 3 to exit): bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
Your selection was invalid. Try again.
Enter your selection (1, 2, 3 to exit): 33
Your selection was invalid. Try again.
Enter your selection (1, 2, 3 to exit): 1
Your choice was 1
Enter your selection (1, 2, 3 to exit): 2
Your choice was 2
Enter your selection (1, 2, 3 to exit): 3
Your choice was 3
E:\Documents and Settings\David\My Documents\Visual Studio 2005\Projects\Menu\de
bug>