Question

This is a program that reads an ip address from stdin and then checks if it is correct. the function "getchar" is only linked to the variable "ch" and not in variable "temp", how is it used to check the input? What i mean is, isn't the ip address saved to "ch", how is saved to "temp" variable also? (if I use printf for temp also, it displays the last character of the ip address I entered)

#include <stdio.h>
int main()
{
    int ch, dots, bytes, temp;

    dots = bytes = temp = 0;
    printf("Enter IP address (x.x.x.x): ");

    while((ch = getchar()) != '\n' && ch != EOF)
    {
        if(ch < '0' || ch > '9')
        {
            if(ch == '.')
            {
                dots++;
                if(temp != -1)
                {
                    if(temp > 255) /* code doesnt work if "temp" here is changed into "ch" */
                    {
                        printf("Error: The value of each byte should be in [0, 255]\n");
                        return 0;
                    }
                    bytes++; 
                    temp = -1;  
                }
            }
            else
            {
                printf("Error: Acceptable chars are only digits and dots\n");
                return 0;
            }
        }
        else
        {
            if(temp == -1)
                temp = 0; 
            temp = 10*temp + (ch-'0'); 
        }
    }
    if(temp != -1)  
    {
        if(temp > 255)
        {
            printf("Error: The value of each byte should be in [0, 255]\n");
            return 0;
        }
        bytes++;
    }
    if(dots != 3 || bytes != 4)
        printf("Error: The IP format should be x.x.x.x\n");
    else
        printf("The input address is a valid IPv4 address\n");


    return 0;
}
Was it helpful?

Solution

In the line you indicated, temp needs to be used because it's giving you information about the current number being read in (basically it's either -1 if it was a dot or the accumulated number if it was a number : temp = 10*temp + (ch-'0');).

Obviously, you can't just be looking at ch because then you'd have no way to check if the number was too high (IP-type numbers need to be from 0 to 255).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top