我正在尝试从用户输入基本的ip地址,但是我的命令在scanf中被卡住了,之后没有执行任何操作。
int ip1,ip2,ip3,ip4;
scanf("%d.%d.%d.%d",&ip1,&ip2,&ip3,&ip4);
printf("Here");
所以,基本上"在这里"永远不会打印,命令scanf永远不会结束?
#include <stdio.h>
#include<math.h>
int main(void) {
char input;
char rep = 'r';
char quit = 'q';
char first = '1';
char second = '2';
input = rep;
while( input != quit) {
printf("What type of conversion do you want? \n");
printf("Enter 1 for 32-bit number to dot-decimal conversion, 2 for the inverse of operation: ");
char val;
scanf(" %c", &val);
if( val == first) {
} else if( val == second) {
printf("\nEnter dot-decimal IP address:");
int ip1,ip2,ip3,ip4;
scanf(" %d.%d.%d.%d", &ip1,&ip2,&ip3,&ip4);
printf("Here");
unsigned int ip = 0,c,k,counter = 31;
for(c = 7; c >= 0; c--) {
k = ip1 >> c;
if(k & 1) {
int temp = 2,i;
for(i = 0; i < counter;i++) {
temp *= 2;
}
ip += temp;
counter--;
}
}
for(c = 7; c >= 0; c--) {
k = ip2 >> c;
if(k & 1) {
int temp = 2,i;
for(i = 0; i < counter;i++) {
temp *= 2;
}
ip += temp;
counter--;
}
}
for(c = 7; c >= 0; c--) {
k = ip3 >> c;
if(k & 1) {
int temp = 2,i;
for(i = 0; i < counter;i++) {
temp *= 2;
}
ip += temp;
counter--;
}
}
for(c = 7; c >= 0; c--) {
k = ip4 >> c;
if(k & 1) {
int temp = 2,i;
for(i = 0; i < counter;i++) {
temp *= 2;
}
ip += temp;
counter--;
}
}
printf("%u is the IP Address",ip);
}
printf("\n \n Enter r to repeat, q to quit:");
scanf(" %c",&input);
}
return 0;
}
这正是我正在做的事情。当我尝试以十进制表示法获取IP地址时,它会被卡住。
答案 0 :(得分:1)
我在更新后分析了您的代码(完整代码),发现问题不在scanf
的输入中,而是在获取数据后执行的for
循环中。
看看那个循环:
unsigned int ip = 0,c,k,counter = 31;
for(c = 7; c >= 0; c--) {
k = ip1 >> c;
if(k & 1) {
int temp = 2,i;
for(i = 0; i < counter;i++) {
temp *= 2;
}
ip += temp;
counter--;
}
}
,特别是在for(c = 7; c >= 0; c--)
,考虑到c
的类型为unsigned int
...我看到此循环为INFINITE,因为减少了0
新的正值UINT_MAX
(见limits.h)。