扫描和计数字符串时出现问题

时间:2020-11-09 13:48:24

标签: c for-loop fgets

我正在尝试创建一个程序来接收用户的文本并计算每个字母被写了多少次。要停止用户输入*的数据输入,我使用了dowhile循环来完成此操作,但是每次插入该循环时,扫描和计数字符的功能都会停止工作,该怎么办? 谢谢= D

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define LIM 1000

int main()
{
  int i = 0 ,h = 0 ,k = 0 , count[26] = {0}, num[26] = {0};
  char c[1000];
  char text;

  printf("Enter a text:\n");
  do{
  fgets(c, sizeof(c), stdin);
  }while(text[c] !='*');
  

  printf("\nDo you want to differentiate between upper and lower case?\n"
         "1 = YES, 0 = NO.\n");
  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 is used %d times in the text.\n",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')
        num[c[k]-'A']++;
      k++;
    }
    
    printf("\nLowercase:\n");

    for (i = 0; i < 26; i++){
      if (count[i] != 0)
        printf("%c is used %d times in the text.\n",i+'a',count[i]);   
    }

    printf("\nUppercase:\n");
    
    for (k = 0; k < 26; k++){
      if (num[k] != 0)
        printf("%c is used %d times in the text.\n",k+'A',num[k]);      
    }

    return 0;
  }
}

我在控制台上得到了

> Enter a text: aaabbb 
> *
> 
> Do you want to differentiate between upper and lower case?  1 = YES, 0 = NO. 
> 1
> Lowercase:
> 
> Uppercase:

1 个答案:

答案 0 :(得分:0)

do / fgets循环将覆盖您的c[]字符数组。键入*表示输入结束的那一刻,您之前的文本消失了。另外,text[c]c[text](C语言中的一个怪癖),并且文本未初始化,因此发生了未定义行为。重新考虑如何输入文本。为什么不简单地用单个fgets(c, sizeof c, stdin)输入一个字符串?

相关问题