I have this code, that prompts the user to enter a 2D vector, and I want to build in error protection so if a character, symbol, etc is entered instead of a character, it prints an error and prompts again. Assuming that this code works perfectly:
vect getVector(void)
{
vect temp;
bool flag = false; /* For repetition we use an
* input flag initialized to false */
while (flag == false)
{
printf("Enter a vector in the format x y: ");
if((scanf("%f%f", &temp.x, &temp.y)) != 2)
printf(" >Input Failure!\n");
else
flag = true; /* Input OK */
clearBuffer(); /* A function I defined elsewhere */
}
return temp;
}
Entering something like "1.w 2.5" or "a.c 3.2" works fine with the error protection. However, entering "1.2 3.c" or "1.6 2.54p" (anything ending with a character) it simply ignores and discards that character. "1.2 3.c" reads "1.2 3.0", "1.6 2.54p" reads "1.6, 2.54" and so on.
How can I build in protection to detect this trailing character and print the error message? Hopefully I cana build something easily into what I've already got.
I've been suggested to store the input in a character string and test for the ASCII codes, and if they're in the range of numbers, then convert them back to float, but I have no clue how that could be done. Moreover I would like to know WHY the code ignores that trailing character, maybe I can then think of a solution myself. Maybe try detecting the character initially? Sorry if it's a silly question, I just can't wrap my head around it.