Hello I am new to C++ but am currently working as a C# programmer (whatever that means) and I am having a bit of trouble.
I have been reading the beginners Tutorials of this site(Cprogramming.com) and I am up to lession 5, switch case, relativly simple, nothing really different so far, or so I thought.
I have created a simple numbers program that request the user enter a number and then it tells the user if the number is higher, lower, or equal to 5(for no other reason then 5 is the first number that poped in my head). but somehow after entering the switch statement I have created an infinate loop that skips the user input statements. well to be more accuract it skips the cin >> veriable; statement because it prints the prompt to enter a number, when I enter say a letter instead of a number. e.g. if I enter a, it goes into the switch statement and prints the error message and then loops. personally I think that the program should just crash if I enter a letter instead of a number unless I do some sort of error trapping considering how I am storing a char in an int, so if someone could explain why that works too that would be nice.
I am using Code;;Blocks 10.05 as my compiler
and this is my code:
Code:
//libraries to be included
#include <iostream>
using namespace std;
//Function prototypes
int DissplayNumber(int firstNumber);
void GreaterThen();
void EqualT0();
void LessThen();
int main()
{
int firstNumber = 1; //Variable which holds the users input.
while(firstNumber != 0) //The Main loop which runs the program until the user enters 0 to exit.
{
firstNumber = DissplayNumber(firstNumber);
}
return 0;
}
int DissplayNumber(int firstNumber)
{
cout << "Please enter a number, or enter 0 to exit:"; /* Propts the user to enter a Number */
cin >> firstNumber; // reads the users input and stores it in firstNumber.
cin.ignore(); //used to get ride of return keystroke, I guess that is useful.
switch(firstNumber)
{
case 0: //if the user enters 0 exit the program.
cout << endl << "Good bye cruel world!";
return firstNumber;
break;
case 5: //if the user enters 5 tell them they entered 5.
EqualT0();
break;
default: // if the user enters anything but a number, display error and restart.
cout << endl << "Error, bad input.";
firstNumber = 1;
return firstNumber;
break;
}
if(firstNumber > 5) // if the number is greater then 5 call GreaterThen
{
GreaterThen();
}
else if(firstNumber < 5)// if the number is less then 5 call LessThen
{
LessThen();
}
cout << endl << "Your number is: " << firstNumber << endl;
return firstNumber;
}
void GreaterThen()
{
cout << endl << "Your Number is Greater then 5.";
}
void EqualT0()
{
cout << endl << "Your Number is 5";
}
void LessThen()
{
cout << endl << "Your Number is Less then 5";
}
Again, thank you for taking the time, and if this has been explained somewhere else forgive me, and simply post a link to that location, and feel free to add the word noob a few times.
-William