简体   繁体   English

为什么显示随机数? C程序读取字符串字母

[英]Why is it showing random numbers? C program to read string letters

So I have to create a program that reads the user input and shows how many times each letter appears in that string, and also how many non-letters but my code for alphabets is showing random numbers.. 因此,我必须创建一个程序来读取用户输入,并显示每个字母在该字符串中出现的次数,以及多少个非字母,但我的字母代码显示的是随机数。

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

#define SIZE 100

void readInput (char string[]);
void Calc(char string[], int letters[]);

void
readInput (char string[])
{
    printf ("Enter a String:\n");
    fgets (string, SIZE, stdin);

    string[strlen (string) - 1] = '\0';
}

void
Calc(char string[], int letters[])
{
    int c = 0, x;
    while (string[c] != '\0')
    {
        if (string[c] >= 'a' && string[c] <= 'z')
        {
            x = string[c] - 'a';
            letters[x]++;
        }

        c++;
    }

    for (c = 0; c < 26; c++)
        printf ("%c occurs %d times in the entered string.\n", c + 'a', letters[c]);
}

int
main ()
{
    char string[SIZE];
    int letters[26];

    readInput (string);
    Calc(string, letters);
    return 0;
}

This is the output 这是输出

I'm new to strings I've googled examples but can't seem to find whats wrong with my code and no idea how I will include the non-letters part. 我是刚接触过示例的字符串的新手,但似乎找不到我的代码有什么问题,也不知道我将如何包含非字母部分。

The contents of letters are not initialised . letters的内容未初始化 Formally the behaviour of your program is indeterminate . 形式上,程序的行为是不确定的

Sort that by writing int letters[26] = {0}; 通过写int letters[26] = {0};排序int letters[26] = {0}; Doing that sets all elements to zero, which is what you want in this case. 这样做会将所有元素设置为零,在这种情况下,这就是您想要的。

letters[] is uniinitialized. letters[]被初始化。 Solution int letters[26]={0} . 解决方案int letters[26]={0}

You are reading an uninitialized value which is indeterminate. 您正在读取一个不确定的未初始化值。 And the results doesn't conform to as you expect it to be. 结果并不符合您的预期。

Here you want to initialize the elements with 0 denoting that you haven't seen any charcaters yet. 在这里,您要使用0初始化元素,表示您尚未看到任何字符。 (automatic storage duration). (自动存储时间)。

A better way to overwrite the '\\n' would be 覆盖'\\n'更好方法是

string[strcspn(string, "\n")] = 0;

您应该使用所有0值初始化letters

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

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