gets比較危險(緩沖區溢出),改用其他函數,比如fgets,不過fgets不會去除結尾的換行符,記得用buf[strlen(buf) - 1] = '';
象你寫的gcc -o match_char match_char.c
雖然有警告,但是match_char已經編譯好了,你運行一下看看
[root@localhost c]# ./match_char
asdfghj
dj
asdfghj
dj
-1
[root@localhost c]# ./match_char
aasdfgh
sd
aasdfgh
sd
3
[root@localhost c]#
[root@localhost c]# ./match_char
as
asfg
as
asfg
-1
[root@localhost c]#
其實這個程序我是看不懂。
書上說 break是跳出循環.
if(flag == -2)
{ flag=i+1;break;}
和
for (j=0;j<nb;j++)
if (a[i+j] != b[j])
{ flag=-1;break;}
分別是跳出到哪里?特別是上面那個?
你給的函數不會用buf是什么意思?
#include <stdio.h>
#include <string.h>
main()
{
char a[80], b[40];
int na, nb, i, j, flag;
gets(a);
gets(b);
na=strlen(a);
nb=strlen(b);
flag = -1;
for(i = 0; na - i >= nb; i++){
flag = -2;
for(j = 0; j < nb; j++)
if (a[i+j] != b[j]){
flag = -1;
break; /* 跳出for(j = 0; j < nb; j++) */
}
if(flag == -2){
flag = i + 1;
break; /* 跳出for(i = 0; na - i >= nb; i++){ */
}
}
printf("%s\n%s\n%d\n", a, b, flag);
}
“你給的函數不會用buf是什么意思?”
這個沒看懂,什么不會用buf?
buf是接收輸入的緩沖區,比如
char buf[80];
fgets(buf, 79, stdin);
buf[strlen(buf) - 1] = '';
比如你輸入"12345",然后回車,程序實際接收到的輸入是"12345\n",用gets的時候gets會去除結尾的'\n',而fgets不會去除結尾的'\n',
buf[strlen(buf) - 1] = '';
的作用是把字符串的最后一個字符('\n')去掉。
相應的,puts輸出的時候會在輸出的字符串結尾加上'\n',fputs就不會。