程序作用:输入一行字符,输出最长的单词
#include <stdio.h>
#include <string.h>
#define N 50
void reverse(char[]);
int main(){
char a[N];
gets(a);
reverse(a);
return 0;
}
void reverse(char a[]){
char temp1[N][N]={0};
int i=strlen(a);
int max=0;//记录最长的长度
int temp=0;//记录每个单词长度
int n=0;//每个单词对应行数
int h=0;//记录最长单词所在位置
for(int j=0;j<i;j++){
if(a[j]==' '){
if(temp>max){
max=temp;//记录当前最长长度
h=n;//记录当前最长单词的行号
}
n++;//存入下一个单词
temp=0;
}
else{
temp1[n][temp]=a[j];
temp++;
}
}
if(temp>max){//如果最长的单词是最后一个
h=n;
}
int longest=strlen(temp1[h]);
puts("最长单词是:");
for(int j=0;j<longest;j++){
printf("%c",temp1[h][j]);
}
}
起初写程序,没有将数组初始化,输出时有时正确,有时有意料之外的字符被输出,debug,发现是 strlen(temp1[h]) 的结果不正确,但加断点逐步执行并没有发现问题,排除程序逻辑问题之后,去检查数组temp1中存的内容,发现有未知字符被存入。至此才想到,数组若未进行初始化,里面会有无法预料的内容存入,若不为‘\0’,则会影响函数strlen()计算结果的正确性。
在写程序遇到bug,debug时首先想到的是语法和逻辑错误,这种惯性思维使我很难发现这种难以预料的错误,以此作为一次经验教训。