printf("try again (y/n)? \n");
scanf("%c", &ans);
printf("Your answer was: %c \n", ans);
printf("Please enter the IP address: \n");
scanf("%d%d%d%d", &IP_oct1, &IP_oct2, &IP_oct3, &IP_oct4);
printf("Please enter the subnet mask: \n");
scanf("%d%d%d%d", &SUB_oct1, &SUB_oct2, &SUB_oct3, &SUB_oct4);
This works as expected but when I change the code by moving the order of line execution as follows:
printf("Please enter the IP address: \n");
scanf("%d%d%d%d", &IP_oct1, &IP_oct2, &IP_oct3, &IP_oct4);
printf("Please enter the subnet mask: \n");
scanf("%d%d%d%d", &SUB_oct1, &SUB_oct2, &SUB_oct3, &SUB_oct4);
printf("try again (y/n)? \n");
scanf("%c", &ans);
printf("Your answer was: %c \n", ans);
It skips over or totally ignores the third scanf ststement. Who can assist me by telling me why?
scanf is a function I don't like. I many cases I don't get what I expect.
You should write the scanf-function like this:
scanf("%d.%d.%d.%d", &IP_oct1, &IP_oct2, &IP_oct3, &IP_oct4);
The scanf-function for scanf("%c", &ans); works correct but not as you expect. The scanf before has read the input-stream until the last digit of last number of your input. So this scanf reads the next char in your input-stream which is the LF of this line. The easist way to solve this problem is accept only the characters 'y' nad 'n' and throught all other away.
PS: If I use then scanf feature I prefer to read a string with the gets-function and scan the string with the sscanf-function.
printf("try again (type 1 for yes or 2 for no.)?");
scanf("%d", &ans);
if(ans == 1)
goto here;
else {
printf(" Good Bye!!!!!!!!! \n\n"); }
Allen,
Changed the code as above despite my reluctance since I could not find a \n (line feed) charcter causing the issue with scanf and %c placeholder as noted in my previous posting. This works awkwardly but gets around that problem. Thanks very much for your feedback and input.
I meant Alex, sorry!
Quote from: CMonger on April 13, 2010, 09:22:09 PM
I meant Alex, sorry!
Don't mind. ;)
If you want your old question, here is my code for this
#include <stdio.h>
#include <io.h>
int main()
{
int IP_oct1, IP_oct2, IP_oct3, IP_oct4;
int SUB_oct1, SUB_oct2, SUB_oct3, SUB_oct4;
char ans;
do
{
printf("Please enter the IP address: \n");
scanf("%d.%d.%d.%d", &IP_oct1, &IP_oct2, &IP_oct3, &IP_oct4);
printf("Please enter the subnet mask: \n");
scanf("%d.%d.%d.%d", &SUB_oct1, &SUB_oct2, &SUB_oct3, &SUB_oct4);
fflush(stdin);
printf("try again (y/n)? \n");
scanf("%c", &ans);
printf("Your answer was: %c \n", ans);
} while (ans == 'c');
}