【问题标题】:Finding frequency of characters both upper case and lower case in a file c program在文件c程序中查找大写和小写字符的频率
【发布时间】:2016-06-07 19:40:22
【问题描述】:

我尝试了很多东西,但是当我选择 2 来分别计算大写和小写时,结果是垃圾,我不知道这有什么问题,而不管是小写还是大写仍然可以正常工作。

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

int main()
{
  int i,h,k ,count[26] = {0}, nam[26] = {0};
  char c[1000];
  FILE *fptr;
  fptr=fopen("tep1.txt","w");
  if(fptr==NULL){
    printf("Error!");
    exit(1);
  }
  printf("a String please:\n");
  gets(c);
  fprintf(fptr,"%s",c);
  fclose(fptr);
  printf("discern between upper case and lower case? 0=no, 1=yes");
  scanf("%d",&h);

  if(h==0){    
    while (c[i] != '\0'){     
      if (c[i] >= 'a' && c[i] <= 'z') 
        count[c[i]-'a']++;

      if (c[i]>='A' &&c[i]<='Z')
        count[c[i]-'A']++;
      i++;
    }

    for (i = 0; i < 26; i++){
      if (count[i] != 0)
        printf("%c %c appears %d times on file.\n",i+'a',i+'A',count[i]);
    }
    return 0;
  }
  if(h==1){    
    while (c[i]|c[k] != '\0') {      
      if (c[i] >= 'a' && c[i] <= 'z') 
        count[c[i]-'a']++;
      i++;
      if (c[k]>='A' &&c[k]<='Z')
        nam[c[k]-'A']++;
      k++;
    }

    for (i = 0; i < 26; i++){
      if (count[i] != 0)
        printf("%c %c appears %d times on file.\n",i+'a',count[i]);      
    }

    for (k = 0; k < 26; k++){
      if (nam[k] != 0)
        printf("%c %c appears %d times on file.\n",k+'A',nam[k]);      
    }

    return 0;
  }
}

【问题讨论】:

  • 也添加输出,以便我们澄清您的问题。
  • w 和(一些未知字符)在文件中出现 26856400 次
  • 您的代码没有任何问题。 ideone.com/dOfdEh
  • int i,h,k : ik 需要初始化。 printf("%c %c appears %d times on file.\n",i+'a',count[i]);printf("%c %c appears %d times on file.\n",k+'A',nam[k]); 参数不匹配。
  • 感谢您的帮助Avinash,尝试选项1,选项0没有问题

标签: c algorithm uppercase lowercase


【解决方案1】:
  • 首先,您必须初始化整数,例如 i = 0
  • 第二件事是计算大小写,问题出在打印中。在打印函数中,您已经写了两次 %c 和一次 %d,但只给出了两个参数。
  • 只需替换您的 printf 函数,

    printf("%c %c appears %d times on file.\n",i+'a',count[i]);

    printf("%c appears %d times on file.\n",i+'a',count[i]);,你的问题就解决了。

【讨论】:

  • 哇,谢谢,没想到这么简单,祝你有美好的一天
【解决方案2】:

这部分代码有不少问题:

while (c[i]|c[k] != '\0') 
{
  if (c[i] >= 'a' && c[i] <= 'z') 
     count[c[i]-'a']++;
  i++;
  if (c[k]>='A' &&c[k]<='Z')
     nam[c[k]-'A']++;
  k++;
}

您不需要两个计数器;您只需要两个数组countnam。你解析每个字母的循环结构应该是一样的。

从代码中退后一步,想想你的循环结构应该做什么。 无论是否注意大小写,都应该以同样的方式遍历该行的字符。

顺便提一下,while 语句中的逻辑是错误的。如果你想要 c[i] 和 c[k] 的任何东西,你会想要的

while (c[i] != '\0' && c[k] != '\0')

你的代码是按位或c[i]c[k] 的值,看看它们是否等于'\0',即等于0。直到ik 是都指向一个空字符,这不会发生很长时间。但同样,您的 while 循环遍历该行应该与 h == 0 的情况相同。

据我所知,您在任何地方都不需要k 柜台。

【讨论】:

  • 我删除了 k 并做了 && 但输出仍然是垃圾。感谢您指出这一点。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-11
  • 1970-01-01
  • 2020-03-01
  • 2013-04-14
相关资源
最近更新 更多