【发布时间】:2015-04-10 11:34:40
【问题描述】:
在下面的程序中,我需要将初始字符和最终字符更改为它们各自的字符,如下所述,但这给了我一个无限循环。我应该怎么做才能修复它?
int main(void)
{
char state ='t';
char word[20]="aaabbccaaaaccbbb";
int initiallength = strlen(word)-1; strcat(word,"a");
while(strlen(word)-1 >initiallength)
{
switch(state)
{
case 't':
switch(word[strlen(word)-1])
{
case 'a':
word[strlen(word)-1]='b'; break;
case 'b':
word[strlen(word)-1]='c'; break;
case 'c':
word[strlen(word)-1]='d'; break;
case 'd':
word[strlen(word)-1]='\0'; break;
}
switch(word[0])
{
case 'a':
word[0]='b'; break;
case 'b':
word[0]='c'; break;
case 'c':
word[0]='d'; break;
case 'd':
word[0]='\0'; break;
}
}
}
}
【问题讨论】:
-
如果您需要任何帮助,请使用代码块格式化此代码。无法按现状阅读。
-
在调试器中运行您的程序并逐行逐行查看它的实际作用。
-
排除任何其他问题,您永远不会更新
initiallength或word的长度,这意味着您需要考虑while 条件strlen(word)-1 >initiallength的作用。 -
@nos ,
word中的 NUL 终止符在某些位置添加。所以strlen(word)会改变 -
也不更新
state所以switch(state)也是没用的
标签: c switch-statement infinite-loop