|
发表于 2023-10-11 15:53:45
|
显示全部楼层
这段代码存在以下问题:
1. gets() 函数已经被标记为不安全,不建议使用,应该使用 fgets() 函数代替。
2. 在 longest_len = –1; 这一行中,减号的符号被使用错误,应该使用负号 - 。
3. 缺少头文件 string.h ,导致编译器无法识别 strlen() 和 strcpy() 函数。
修改后的代码如下:
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #define MAX_LEN 1001 /* Buffer size for longest line */
- int main(void) {
- char input[MAX_LEN];
- int len;
- char longest[MAX_LEN];
- int longest_len;
- longest_len = -1;
- while (fgets(input, MAX_LEN, stdin) != NULL) {
- /*
- ** Get length of this line. If it is longer than the previous
- ** longest line, save this line.
- */
- len = strlen(input);
- if (len > longest_len) {
- longest_len = len;
- strcpy(longest, input);
- }
- /*
- ** If we saved any line at all from the input, print it now.
- */
- if (longest_len >= 0) {
- puts(longest);
- }
- }
- return EXIT_SUCCESS;
- }
复制代码 |
|