In my introductory C class I wrote a program that takes two points on the earths surface and calculates the arc distance between them. I finished up the projects, except that I have one question on input validation which is probaly pretty stupid.
It has to do with one of my input functions that asks the user to enter N or S for latitude and E or W for longitude. The function sends back an integer value to represent the choice of the user. Here is the code for the function:
Code:int northsouth() { char ns_switch; // Character variable of switch that should have a value of N or S int ns_var; // Integer value of 1 or 2 indicating N or S respectively int true_false=0; // Determines when to quit the while loop while (true_false == 0) { printf("Enter N for North or S for South: "); fflush(stdin); scanf("%c", &ns_switch); switch (ns_switch) { case 'N': ns_var=1; true_false=1; break; case 'S': ns_var=2; true_false=1; break; default: true_false=0; printf("\nInvalid Input! Please Try Again! \n"); } } return(ns_var); }
If I enter : N
it works fine
If I enter : S
it works fine
If I enter : (anything that doesn't start with N or S)
it re-does the loop and works fine.
But if I type: Newew
or : Sd323
or : NS
The loop will still quit.
So my question is, How do I fix my program so that it will only accept (N or S) period. If something is typed after N or S, I want the program to see it as invalid input.
thank you for the help,
Zack