从文件中计算字母“ s”和“ S”

时间:2019-12-10 02:36:29

标签: c function loops file-io

我正在做一个作业,我必须读取c中的文件并计算txt文件中有多少个“ s”或“ S”。我几乎完成了分配工作,但是在计算函数int CountLetterS(char Str[1000])中的字母's'时遇到了麻烦。现在,分配需要一个计算“ s”数量的函数。我没有执行该函数,并且代码按预期运行。代码中有一个块注释。运行带有块注释且不带功能的函数,可以为我提供所需的输出。但我不知道如何使用该功能。它输出到Count: 4。但是它应该输出到Count: 950


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int CountLetterS(char Str[1000]){
    int countLetter = 0;
    int i = 0;

    for (i = 0; i < strlen(Str); i++) {
       if (Str[i] == 's' || Str[i] == 'S'){
                countLetter++;
            }
        }
    return countLetter;
}


int main() {

    FILE* fp = NULL;
    fp = fopen("slow_glass.txt", "r");
    if (fp == NULL){
        printf("File did not open");
        exit(1);
    }

    char str[1000];
    int count = 0;

    while (fgets(str, 1000, fp) != NULL){
        count = CountLetterS(str);
    }


/*
    while (fgets(str, 1000, fp) != NULL){
        for (int i = 0; i < strlen(str); i++) {
        if (str[i] == 's' || str[i] == 'S'){
                 count = count + 1;
             }
         }
    }

*/

    printf("Count: %d\n", count);

    fclose(fp);

    return 0;
}

1 个答案:

答案 0 :(得分:0)

每次调用CountLetterS()函数时,count变量都会获得新值。 因此,您要打印的计数只是文本文件的最后一部分。

代替使用:

int count = 0;
count += CountLetterS();

或其他方法。

不需要获取,而是使用fgetc。

int CheckForS(char    ch)
{
  if(ch == 'S' || ch == 's')
  {
      return 1;
  }
  else
  {
      return 0;
  }
}

在main()内部

while ((c = fgetc(file)) != EOF)
{
    count += CheckForS(c);
}