Write a program (in C) that asks for the IP address in a human readable form, creates three substrings, and prints them.
These substrings are created from parts 3, 2, and 1 of the last part of the IP address.
These substrings should be created with the use of pointers or array indexing (whichever you prefer). If a given string doesn't have three dots, then the program should print the message: Error: not a valid address..
Your program should also check if a given string consists only of digits and dots, and that there are no more than three digits in each block. You don't have to check if the numbers are smaller than 256.
Your version of the program must print the same result as the expected output.
I write this code below, but isn't working:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define LUNG 30
#define INTLUNG 30
void controlla(char *str){
char pt1[INTLUNG],pt2[INTLUNG],pt3[INTLUNG],pt4[INTLUNG];
int i=0,j=0;
while(str[i] !='.' && str[i] != '\0')
{
pt1[j]=str[i];
i++;
}
i++;
while(str[i] !='.' && str[i] != '\0')
{
pt2[j]=str[i];
i++;
j++;
}
j=0;
i++;
while(str[i] !='.' && str[i] != '\0')
{
pt3[j]=str[i];
i++;
j++;
}
j=0;
i++;
while(str[i] !='.' && str[i] != '\0')
{
pt4[j]=str[i];
i++;
j++;
}
printf(pt1);
printf(pt2);
printf(pt3);
printf(pt4);
}
int main(){
char str[LUNG];
printf("Inserisci un indirizzo ip:\t");
fgets(str,LUNG,stdin);
controlla(str);
return 0;
}
ptX
to see if it's a digit.j
after each loop.j = 0
before each while
loop..
, not \0
. Otherwise you'll keep reading past the end of the string.\n
instead of .
.printf()
should be a format string, not the string you want to print.#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define LUNG 30
#define INTLUNG 30
void controlla(char *str){
char pt1[INTLUNG],pt2[INTLUNG],pt3[INTLUNG],pt4[INTLUNG];
int i=0,j=0;
while(str[i] !='.' && str[i] != '\0')
{
if (!isdigit(str[i])) {
printf("Not a valid address\n");
return;
}
pt1[j]=str[i];
i++;
j++;
}
if (i == 0 || str[i] != '.' || j == 0 || j > 3) {
printf("Not a valid address\n");
return;
}
i++;
pt1[j] = '\0';
j = 0;
while(str[i] !='.' && str[i] != '\0')
{
if (!isdigit(str[i])) {
printf("Not a valid address\n");
return;
}
pt2[j]=str[i];
i++;
j++;
}
if (str[i] != '.' || j == 0 || j > 3) {
printf("Not a valid address\n");
return;
}
i++;
pt2[j] = '\0';
j=0;
while(str[i] !='.' && str[i] != '\0')
{
if (!isdigit(str[i])) {
printf("Not a valid address\n");
return;
}
pt3[j]=str[i];
i++;
j++;
}
if (str[i] != '.' || j == 0 || j > 3) {
printf("Not a valid address\n");
return;
}
i++;
pt3[j] = '\0';
j=0;
while(str[i] != '\n' && str[i] != '\0')
{
if (!isdigit(str[i])) {
printf("Not a valid address\n");
return;
}
pt4[j]=str[i];
i++;
j++;
}
pt4[j] = '\0';
if (j == 0 || j > 3) {
printf("Not a valid address\n");
return;
}
printf("%s %s %s %s\n", pt1, pt2, pt3, pt4);
}
int main(){
char str[LUNG];
printf("Inserisci un indirizzo ip:\t");
fgets(str,LUNG,stdin);
controlla(str);
return 0;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句