Hi all,
I'm studying Acoustics at Salford and i'm currently working on C++ programming.
I've hit a brick wall with my coding, i know exactly what i want it to do, just haven't been taught enough and need some help rectifying an issue.
If a question requires a numerical (int) input by the user, but for some reason they input a char, how do i let the program know what to do? Im currently using this code for the method:
#include <iostream>
using namespace std;
int choice_unit=0, choice_weapon=0, choice_term=0, weapon_num=1;
void main()
{
//Unit choice question
cout<<"Are you using Metric or Imperial values?";
cout<<"\n1. Metric\n2. Imperial\n";
cin>>choice_unit;
//Catches char inputs due to errors
if(!(cin >>choice_unit))
{
cin.clear();
cin.ignore(255,'\n');
}
cout<<"\n";
//Catch if number is not 1 or 2 also reset input to 0
while(!(choice_unit==1 || choice_unit==2))
{
cout<<"ERROR: Incorrect input. Please enter 1 or 2\n";
cin>>choice_unit;
if(!(cin >>choice_unit))
{
cin.clear();
cin.ignore(255, '\n');
choice_unit=0;
}
else
{
cout << choice_unit;
cout<<"\n";
}
cout<<"\n";
}
system ("PAUSE");
}
Basically, the output of this code after the following by the user:
cin>>//some char
cin>>//correct value (1 or 2)
doesn't result in the program flowing and the user actually needs to enter the correct value a second time for it to work. What am i doing wrong and how do i rectify this?
Many thanks in advance for save me from insanity.
ps im a complete newbie to C++!!!