为什么我的代码在输出中显示奇怪的数字?

Why is my code displaying bizzare numbers in the output?

这是一个打印输入中不同字符频率直方图的程序。它将大小写字母一起计算。

字符应按其 ASCII 值的升序打印。

#include<string.h>
#include<stdio.h>
#include<ctype.h>
int main()
{
    char str[100], new[100];  
    int  i,j,count=0,n;
    char temp; 

    fgets(str, 100, stdin);

    //convert upper chars to lower chars
    for(i=0;i<strlen(str);i++){
        new[i] = tolower(str[i]);

    }    

    //assign n to the length of the string
    for(j=0;new[j];j++);
    n=j; 

    //sort the string in ascending order
    for (i = 0; i < n-1; i++) {
        for (j = i+1; j < n; j++) {
            if (new[i] > new[j]) {
                temp = new[i];
                new[i] = new[j];
                new[j] = temp;
            }
        }
    }

    //check and print the count
    for(i=0;i<n;i++)  
    {
        count=1;
        if(new[i])  
        {
          for(j=i+1;j<n;j++)  
          {   
            if(new[i]==new[j])
            {
                 count++;
                 new[j]='[=10=]';   //make the sec char 0
            }
          }  
          printf("%c %d \n",new[i],count);
       }
    } 


    return 0;
}

for(j=0;new[j];j++); 失败,因为 new 不是 字符串

空字符 从未在 for(j=0;new[j];j++);

之前的 new[] 中赋值

不清楚输出中的奇怪数字是什么意思。所有字符数看起来都是正确的。

如果你的意思是输出开头的奇怪 1,那么我认为 "gotcha" 是你的输入(和输出)包含换行符。

> man fgets

fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer.

所以当你对字符进行排序时,换行符将排在第一位。

您可以通过几种不同的方式解决这个问题,但一个简单的方法是只输出可打印字符,例如

    if(isprint(new[i]))  
        printf("%c %d \n",new[i],count);