简体   繁体   English

用户在逐字符扫描的字符串中进行无限输入

[英]Infinite Input by user in an string scanned by character by character

I'm trying to create a program that will count the frequency of the character and printf it along with the character. 我正在尝试创建一个程序,该程序将计算字符的频率并将其与字符一起打印。

However for a given string my program is taking infinite input of the last character. 但是对于给定的字符串,我的程序将无限输入最后一个字符。

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

struct value
{
    long long as;
    long long k;
};

int main()
{
    long long count[128] = {0};
    char c;
    struct value max;
    max.k = 0; max.as = -1;

    // Upto Here was only initialization.

    while(1)
    {

        scanf("%c",&c);
        printf("%c",c);
        if(c!='\n')
        {
            count[c]++;
            if(max.as<count[c])
            {
                max.as = count[c];
                max.k = c;
            }
            if(max.as==count[c]&&max.k<c)
            {
                max.k = c;
            }
        }
        else break; // Apparently this is never executed.
    }

     printf("\n%c %lld",(char)(max.k),max.as);
}

Like for the input "masaka" here gives output as "masakaaaaaaaaaaaaaaaaaa" where a is printed until output limit is reached. 就像输入“ masaka”一样,此处将输出显示为“ masakaaaaaaaaaaaaaaaaaaaaaa”,其中将打印a直到达到输出限制。

Why is this happening here? 为什么会在这里发生?

Your program will loop if the input does not have a newline in it, since it doesn't check for EOF. 如果输入中没有换行符,则程序将循环,因为它不会检查EOF。

scanf() will return EOF if it reaches end-of-file before parsing any inputs. scanf()在解析任何输入之前到达文件末尾,则将返回EOF

while(1)
{

    int result = scanf("%c",&c);
    if (result == EOF || result == 0) {
        break;
    }
    printf("%c",c);
    if(c!='\n')
    {
        count[c]++;
        if(max.as<count[c])
        {
            max.as = count[c];
            max.k = c;
        }
        if(max.as==count[c]&&max.k<c)
        {
            max.k = c;
        }
    }
    else break; // Apparently this is never executed.
}

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

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