我有一个像这样声明的函数的一部分:
char keystroke;
printf("\n(a)dd, (d)elete, or (m)odify (use - and + to navigate left and right)");
keystroke = getchar();
switch (keystroke){...
无论出于何种原因,我无法继续进入switch语句。输出如下:
(a)dd, (d)elete, or (m)odify (use - and + to navigate left and right)eginning at (5,6)
s
s
s
a
a
a
f
后面的字符是我尝试输入的。 gdb说No symbol "keystroke" in current context
所以我猜它是不是因为某些原因被记录了?知道为什么吗?
编辑:
这是有问题的功能。它有点长并涉及,并使用一些全局变量。
struct inputlist{
int coords[2];
struct inputlist *next;
};
input *head;
typedef struct inputlist input;
void inpt()
{
input *temp=head;
input *temp2;
char keystroke;
int cursor = 0;
int counter = 0;
int i;
int impx[2]= {0};
int impy[2]= {0};
int end = 0;
if(temp)
while(temp->next)
temp = temp->next;
while(1)
{
printf("Please enter the x coordinate or s to stop.");
if(!scanf("%d",impx))
break;
if((!impx[0]<=0)&&(!impx[0]>=7))
{
printf("Please enter a number: [0,7]");
continue;
}
printf("Please enter the y coordinate or s to stop.");
if(!scanf("%d",impy))
break;
if((!impy[0]<=0)&&(!impy[0]>=7))
{
printf("Please enter a number: [0,7]");
continue;
}
temp2 = malloc(sizeof(input));
if(!temp2)
exit(2);
if(!head)
head = temp2;
temp2->next = NULL;
if(temp)
temp->next = temp2;
else
head = temp = temp2;
temp2->coords[0] = impx[0];
temp2->coords[1] = impy[0];
}
if(!head)
exit(0);
temp = head;
while(!end)
{
int is_correct = 0;
counter = 0;
// printf("\033[");
while(temp->next)
{
if(counter++==cursor)
printf("*");
else
printf(" ");
printf("(%d,%d)",temp->coords[0],temp->coords[1]);
temp = temp->next;
}
printf("\n(a)dd, (d)elete, or (m)odify (use - and + to navigate left and right)");
keystroke = getchar();
switch (keystroke)
{
case 'a':
while(temp)
temp=temp->next;
do
{
scanf(" %d",impx);
scanf(" %d",impy);
if ((impx[0]<=7)&&(impx[0]>=0)&&(impy[0]<=7)&&(impy>=0))
{
temp->next = malloc(sizeof(input));
temp = temp->next;
temp->next = NULL;
temp->coords[0] = impx[0];
temp->coords[1] = impy[0];
is_correct = 1;
}
} while(!is_correct);
break;
case 'd':
temp = head;
for(i = 0; i<cursor-1;i++)
temp = temp->next;
temp2= temp->next;
temp->next = temp2->next;
free(temp2);
break;
case 'm':
temp = head;
for(i=0; i<cursor;i++)
temp = temp->next;
do
{
scanf(" %d",impx);
scanf(" %d",impy);
if ((impx[0]<=7)&&(impx[0]>=0)&&(impy[0]<=7)&&(impy>=0))
{
temp->coords[0] = impx[0];
temp->coords[1] = impy[0];
is_correct = 1;
}
} while(!is_correct);
break;
case '+':
case '='://because who wants to hit shift? not me
temp = head;
for(i=0;i<cursor;i++)
temp = temp->next;
if(temp->next)
cursor++;
break;
case '-':
case '_':
if(cursor)
cursor--;
break;
default:
end = 1;
break;
}
}
}
答案 0 :(得分:2)
从while(1)
循环跳出后,输入缓冲区中存在一些失败匹配输入,您需要在进入while (!end)
循环之前使用它们。您可以通过以下方式执行此操作:
while ((keystroke = getchar()) != '\n') ;
如果您没有消费,getchar()
中的while(!end)
会从中读取。
在while(!end)
循环中,如果您输入a
或m
,则需要输入两个整数,没有任何提示,您应该添加一些。