【问题标题】:Counting the number of appearances of each character计算每个角色出现的次数
【发布时间】:2021-01-14 16:18:36
【问题描述】:

我是 C 的新手,正在做作业。我完成了大部分工作,但我无法通过教授使用的所有测试用例。他拒绝发布自动评分器中使用的案例。

我错过了哪些案例? 任何线索将不胜感激!!!

Write a program to remove all the blank characters (space and tab) in a line. 
Then, count the number of appearances of each character.

Input
A single line with a maximum length of 5000 characters
Output
First line: The line after removing all the blank characters. 
If the line is empty, don’t print anything in the output.

Next lines: Each line contains a character that appears in the line and its count. 
Note that, the characters must appear according to their ASCII number order. (http://www.asciitable.com)
#include <stdio.h>
int main (){
    int  c = 0;
    int  characters[128] = {0}; //    subscripts for the ASCII table
    int  count           = 0;   //    number of characters been reading in

    while(count < 5001 && (c = getchar()) != EOF) {
        // 9 -> TAB on ASCII,  32 -> Space on ASCII
        if (c != 9 && c != 32) {
            putchar(c); 
            characters[c]++;
            count++;
        }
    }
    fflush(stdout);
    printf("\n");
    for (int i = 0; i < 128; i++) {
       if (characters[i] != 0) {
           printf("%c %d\n", i, characters[i]);
        }
    }    
    return 0;
}

再次感谢任何帮助!

更新: 代码已更正。

【问题讨论】:

  • 9 字符代表什么?!也许你的意思是if (!isspace(c))。注意输入不与输出交错,所以你可以立即使用putchar(),无需将文本累积到text
  • characters[index] = 0; 为什么?
  • @dxiv 显然应该是text[index] = 0 :D
  • characters[index] = 0; 这意味着如果输入的长度> 256(应该是最大值5000),您的程序将写入数组边界之外
  • 请不要使用magic numbers。如果932 分别表示换行符和空格的ASCII 值,请改用正确的字符常量'\n' ' '

标签: c counting


【解决方案1】:

可能你不想写

  •  characters[index] = 0;
    

你想要的可能是

  •  text[index] = 0;
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多