Hey,
so i posted earlier about my ratio calculator and asked about how to prevent a character from trying to be written into an int/double variable
this is the code we came up with and it works perfect
1 2 3 4 5 6 7 8 9
|
if (cin.fail())
{
cin.clear();
cin.ignore();
system("CLS");
cout << "please enter a nurmeric value" << endl << endl;
}
| |
so after applying this bit of code everywhere that its needed, i set about trying to intentionally break the program any way i could. i could not do so, however i did run into a strage issue that i dont realy understand.
when entering a character into a numeric input, the program behaves as it should- it outputs a message saying that the input is wrong, and loops back to the input request.
now to understand the issue i kinda have to explain the sequence of things, ill also drop the code for it below this paragraph. the sequence is:
-item name request,
-item value request,
-*if correct input type, carry on to next stage (either input another items info, or readback and confirmation of inputed info)
-*if incorect input type loop back up to item name request
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
|
int infograb()
{
for (; counter != Numberofratiovariables;)
{
cout << "please enter the name of item " << counter + 1 << "." << endl;
cin >> itemname[counter];
cout << endl << endl << "please enter the value of " << itemname[counter] << "." << endl;
cin >> b;
if (cin.fail())
{
cin.clear();
cin.ignore();
system("CLS");
cout << "Please only enter numeric values for your item value." << endl << endl;
}
else
{
value[counter] = b;
counter = counter + 1;
system("CLS");
}
}
system("CLS");
return 0;
}
| |
however if there is more then one character inputted, i.e.- gg, the first g is cleared and ignored, and the program loops. however the second g is automatically used as the item name, and the loop starts again at the -item value request position. its as if the second g isnt being cleared and is then being used as the name of the item. this also occurs if i enter a numeric value with a character at the end- i.e. 400g. the program dose not loop as it should, the 400 is used as the value, and the g is automatically entered as the name of the next item.
im assuming this is because i have to add some parameters to the cin.clear(*add parameters here?*)? if thats the case, can someone explain cin.clear() to me? like whats the syntax for adding parameters?
this is litteraly the very last hurdle before i build the program