【发布时间】:2012-06-22 21:11:38
【问题描述】:
我用 C 编写了一个程序,用于查找具有最大字符数的行。
代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
int main (int argc, char *argv[])
{
char c; /* used to store the character with getc */
int c_tot = 0, c_rig = 0, c_max = 0; /* counters of characters*/
int r_tot = 0; /* counters of rows */
FILE *fptr;
fptr = fopen(argv[1], "r");
if (fptr == NULL || argc != 2)
{
printf ("Error opening the file %s\n'", argv[1]);
exit(EXIT_FAILURE);
}
while ( (c = getc(fptr)) != EOF)
{
if (c != ' ' && c != '\n')
{
c_tot++;
c_rig++;
}
if (c == '\n')
{
r_tot++;
if (c_rig > c_max)
c_max = c_rig;
c_rig = 0;
}
}
printf ("Total rows: %d\n", r_tot);
printf ("Total characters: %d\n", c_tot);
printf ("Total characters in a row: %d\n", c_max);
printf ("Average number of characters on a row: %d\n", (c_tot/r_tot));
printf ("The row with max characters is: %s\n", ??????)
return 0;
}
我可以轻松找到字符数最多的行,但如何打印?
【问题讨论】:
-
我认为这里说“行”而不是“行”更正确。
-
请注意:在您的 while 循环中,您将 c 的值与
'\n'进行了两次比较。您可以通过首先移动行检查并使用 else 子句来避免这种情况。在 else 子句中,您只需检查if(c != ' ')。 -
c 应该是 int,而不是 char,因为 EOF 不是 char 值。