这是我的代码,我试图创建一个使用函数对字符进行计数的程序,然后在遇到空行时确定字符的平均值。该程序假定允许用户输入多行,直到遇到空行,但我似乎无法。

#include <stdio.h>
#include <Windows.h>

int main()
{
    char str[1000];
    int Digits, Char, SpecialChar, linecount = 0;
    int counter;
    int total;
    int average;

    Digits = Char = SpecialChar = 0;

    printf("Please type in your words here: ");
    gets(str);

    for (counter = 0; str[counter] != NULL; counter++)
    {

        if (str[counter] >= '0' && str[counter] <= '9')
            Digits++;
        else if ((str[counter] >= 'A' && str[counter] <= 'Z') || (str[counter] >= 'a' && str[counter] <= 'z'))
            Char++;
        else
            SpecialChar++;
    }

    while (str[counter] != '\n')
    {
        if (str[counter] = '\n')
        {
            linecount ++;
        }
    }

    total = Digits + Char + SpecialChar;
    average = total / linecount;

    printf("\nDigits: %d \nCharacters: %d \nSpecial Characters: %d \nLine: %d", Digits, Char, SpecialChar, linecount);
    printf("\nTotal no. of characters = %d", total);
    printf("\nAverage no. of characters = %d", average);

    Sleep(5000000);
    return 0;
}

最佳答案

据我所知,函数“ \ n”后被中断。另外,使用fgets必须注意字符串上的'\ 0'加法。那意味着


  该程序假定允许用户输入多行,直到遇到空行,但我似乎无法。


这种方式永远无法完成。由于不建议使用gets函数,因此我以可能会搜索的方式对您的代码进行了一些编辑。

值得一提的是,在阅读此代码之前,我发现这可能是逻辑错误


  for(counter = 0; str [counter]!= NULL; counter ++)


这似乎很奇怪,因为fget总是记录“ \ n”字符。所以,下一个条件


  如果(str [counter] ='\ n')


永远不会是真的

我在您的代码上看到一些其他错误,但没有专业错误。因此,我认为该建议足以任命他们

while (fgets(str, 1000, stdin) && str[0] != '\n'){ //I dont know if checking the first element of the string is redundancy,
//because, the I think the fgets function will return NULL if you just press enter, as the first character

    for (counter = 0; str[counter] != '\n'; counter++{

        if (str[counter] >= '0' && str[counter] <= '9')
            Digits++;
        else if ((str[counter] >= 'A' && str[counter] <= 'Z') || (str[counter] >= 'a' && str[counter] <= 'z'))
            Char++;
        else
            SpecialChar++;
    }

    linecount ++;  //new line is someting that you will always reach, so,
                  //there is no reason for any condition

}

关于c - 如何输入新行,直到在C中遇到空行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45259984/

10-11 21:06