简体   繁体   English

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

[英]Why is my code displaying bizzare numbers in the output?

This is a program to print a histogram of the frequencies of different characters in its input.这是一个打印输入中不同字符频率直方图的程序。 It counts uppercase and lowercase letters together.它将大写字母和小写字母一起计算。

The characters should be printed in increasing order of their ASCII value.字符应按其 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]='\0';   //make the sec char 0
            }
          }  
          printf("%c %d \n",new[i],count);
       }
    } 


    return 0;
}

这是输出

for(j=0;new[j];j++); fails as new is not a string .失败,因为new不是string

null character never assigned in new[] before for(j=0;new[j];j++); null 字符从未在for(j=0;new[j];j++);之前在new[]中分配;

It's not clear what bizarre numbers you mean from the output. All the counts of characters look correct.不清楚 output 中的奇怪数字是什么意思。所有字符数看起来都是正确的。

If you mean the weird 1 at the start of the output, then I expect the "gotcha" is that your input (and output) includes the newline character.如果您指的是 output 开头的奇怪的1 ,那么我希望“陷阱”是您的输入(和输出)包含换行符。

> man fgets > 男人 fgets

fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. fgets() 从 stream 中最多读入一个小于 size 的字符,存入 s 指向的缓冲区中。 Reading stops after an EOF or a newline.在 EOF 或换行符后停止阅读。 If a newline is read, it is stored into the buffer.如果读取到换行符,则将其存储到缓冲区中。

So when you sort the characters, the newline character will be first.所以当你对字符进行排序时,换行符将排在第一位。

You could solve this a few different ways, but a simple one is to only output printable characters, eg您可以通过几种不同的方式解决这个问题,但一个简单的方法是仅使用 output 个可打印字符,例如

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM