简体   繁体   English

C计算文件中数字和字母的数量

[英]C counting number of numbers and letters from file

int main()
{

    // Defining that we only expect there to be a maximum of 1,000
    // characters per lines read.
    char buffer[1000];
    FILE *pFile;
    char numbers = 0;
    char chars = 0;

    // Opens the file for reading
    pFile = fopen("vstup.txt", "r");

    // fopen returns 1 if an error occurred 
    if (!pFile)
        printf("Error : Couldn't Read the File\n");


    while (fgets(buffer, 1000, pFile) != NULL)
    {

        printf("%s", buffer);

        for (int i = 0; i < 50; i++)
        {
            if (buffer[i] >= '0' && buffer[i] <= '9')
            numbers++;

            if ((buffer[i] >= 'A' && buffer[i] <= 'Z') || (buffer[i] >= 'a' && buffer[i] <= 'z'))
                chars++;
        }

    }


    printf("\nSuccess Reading from File\n");
    printf("\nNum of numbers %d",numbers);
    printf("\nNum of letters %d", chars);

    // Closes the text file
    if (fclose(pFile) != 0)
        printf("Error : File Not Closed\n");

    getchar();

}

I am trying to count number of letters and numbers from file it works for numbers but it doesn't work for letters and next think I am not sure how to right proceed for statement to not waste counts. 我正在尝试从文件中计算字母和数字的数量,它适用于数字,但不适用于字母,接下来认为我不确定如何正确进行声明以免浪费计数。

I will appreciative any help. 我将不胜感激。

Thx guys I did it with fgetc everything works now. Thx伙计们,我用fgetc做到了,现在一切正常。

do
    {
        c = fgetc(pFile);
        if (feof(pFile))
        {
            break;
        }
        printf("%c", c);
        if (c >= '0' && c <= '9')
            numbers++;

        if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'))
            chars++;
    } while (1);

It's unlikely that this program will count anything accurately due to the fact that it's only checking 50 characters per line. 由于该程序每行仅检查50个字符,因此该程序不太可能准确计数任何内容。

I'd suggest changing: 我建议更改:

while (fgets(buffer, 1000, pFile) != NULL)

to: 至:

for (int i = 0; buffer[i] != '\0'; i++)

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

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