[root@localhost c]# gcc match_char.c /tmp/ccONSwnZ.o: In function `main': /tmp/ccONSwnZ.o(.text+0x1b): the `gets' function is dangerous and should not be used. [root@localhost c]# cat match_char.c #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;} if(flag == -2) { flag=i+1;break;} } printf ("%s\n%s\n%d\n",a,b,flag); } [root@localhost c]# 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[strlen(buf) - 1] = ''
基础差,这里的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就不会。 |