0
/* stringlength
 * input: str, pointer to a string
 * output: integer representing the length of string str, 
 * not counting the terminating character.
 *
 * You may NOT call ANY functions within this function.
 */
int stringlength(char *str)
{
    // count the number of characters in str
  int count=0,k;
  for (k=0; str[k] != '\0';k++)
    count++;
    return count;
}

/* countchars
 * inputs: character c, string str
 * output:  The number of instances of c in the string str
 * You may not call ANY function calls within this function.
 */
int countchars(char c, char *str)
{
    // count the number of times c is found in str
  int k,count=0;
  for (k=0;str[k]=='\0';k++)
    {
      if (str[k] == c)
    count++;
      else;
    }

    return count;
}

/* countlines
 * input: char *filename - string containing the filename
 * output: integer representing the number of lines in the file
 */
int countlines(char *filename)
{
    // count the number of lines in the file called filename
  FILE *f = fopen(filename,"r");
    char ch;
    int lines=0;
  f = fopen(filename,"r");

  do{
    ch = fgetc(f);
    if( ch == '\n')
      lines++;
  }while( ch != EOF );

return lines;
}

我需要在我的程序中实现的这三个不同功能的帮助。我是初学者,所以请放轻松,countlines 功能给我带来了最大的麻烦。如果有人能解释为什么不或为什么这些功能会起作用,将不胜感激。

4

1 回答 1

3

有很多问题countlines()

  1. 您打开文件两次,但FILE *用第二个值覆盖了第一个值,因此您无法关闭它。这是一个小问题。

  2. 主要问题是该函数fgetc()返回一个int,而不是一个char。特别EOF是 是一个不同于 each 的值char

  3. 该代码在返回之前不会关闭文件。通常,如果您在函数中打开文件,则应将其关闭。如果不这样做,则必须将文件指针传递回调用代码,以便它可以关闭它。

  4. 对于do ... while输入循环来说,循环很少是正确的(while顶部的循环测试几乎总是更干净更清晰),但至少你没有使用feof().

    int countlines(char *filename)
    {
        FILE *fp = fopen(filename,"r");
        int ch;
        int lines = 0;
        if (fp == 0)
            return lines;
    
        while ((ch = fgetc(fp)) != EOF)
        {
            if (ch == '\n')
                lines++;
        }
    
        fclose(fp);
    
        return lines;
    }
    

当您char改为使用时,会发生以下两种情况之一:

  • 如果您的char类型是signed,那么真正的字符(通常是 ÿ — y-变音符号、U+00FF、带有分音符号的拉丁小写字母 Y)也匹配EOF,因此您可以在到达文件末尾之前停止阅读。
  • 如果您的char类型是unsigned,则任何值都不会匹配EOF,因此循环将永远不会停止。

stringlength()中,您有两个变量countk它们被小心地保持在相同的值;你只需要两者之一。


除了参差不齐的缩进(在所示的代码中很常见——而且绝对是要避免的事情),以及完全没有任何作用的不必要和毫无意义else;的代码,countchars() 看起来不错的代码(后期添加)......在for循环中反转了条件;它应该是str[k] != '\0',当然。

于 2012-09-30T05:17:11.790 回答