Hi All,
I am new to C++. I am practicing loops and i need some help. This one behaves strangely. What i want is for this loop to accept numbers from 1 to 4 for options (strictly numbers) and no other characters. When executed and run, if the input is letters or characters, it clears, dumps the wrong input to a string and loops again asking to enter the right data. But then if i enter the right data (numbers from 1-4), it goes nuts. Does not accept the right number when typed for the first number. I have to enter it again.
Can someone pls explain to me the reason for this and help me correct the code. Thanks.
#include <iostream>
#include <string>
#include <cstdlib> // for system
using namespace std;
int main()
{
int dept_code = 0;
string wrongSelection;
cout << "\nChoose a Department to Proceed. Enter Dept. No. (1,2, 3 or 4)\n";
do
{
cout << "\nDepartments\n-----------\n1) Accounting Dept." << "\n2) Purchasing Dept." << "\n3) Marketing Dept." << "\n4) Technical Dept.\n\n";
cin >> dept_code;
if(!(cin >> dept_code))
if ((dept_code <1) || (dept_code >4))
{
cin.clear();
cin >> wrongSelection; // dump to string
system("clear"); // for Linux / Unix
// system("CLS"); // for Win
cout << "\nInvalid selection! Choose one of the departments between 1 & 4\n";
cout << "\nDepartments\n-----------\n1) Accounting Dept." << "\n2) Purchasing Dept." << "\n3) Marketing Dept." << "\n4) Technical Dept.\n\n";
cin >> dept_code;}
}
while ((dept_code <1) || (dept_code >4));
if (dept_code == 1)
{ cout << "\nYou have chosen Accounting Dept."; }
else if (dept_code == 2)
{ cout << "\nYou have chosen Purchasing Dept."; }
else if (dept_code == 3)
{ cout << "\nYou have chosen Marketing Dept."; }
else if (dept_code == 4)
{ cout << "\nYou have chosen Technical Dept."; }
}