简体   繁体   中英

Reading input from fgetc() and printing with printf()

Okay, I'm sure there's something I'm missing here, but I have no idea what it is and I'm hoping someone could help me figure it out.

I'm reading in input from the command line and was writing a function that uses fgetc() to do so. However, a seemingly superficial change in the function causes it to behave completely differently.

This is the main() function:

while(1)
{
     char* cmd = malloc(sizeof(char) * 80);
     printf("Enter command: ");
     read_flush(cmd, 80);
     printf("%s\n", cmd);
     free(cmd);
}

And this is one of the versions of read_flush():

int read_flush(char* buffer, int count)
{
    int i, c;
    for(i = 0; i < count; i++)
    {
        c = fgetc(stdin);
        if(c == '\n' || c == EOF)
            return i;
        buffer[i] = (char)c;
    }

    return i;
}

This one works fine. You type in input and it will spit it back out. However, this next version causes main to just print "Enter command:" over and over without giving the user a chance to enter input.

int read_flush(char* buffer, int count)
{
    int i, c;
    while(i < count)    
    {
        c = fgetc(stdin);
        if(c == '\n' || c == EOF)
            return i;
        buffer[i] = (char)c;
        i++;
    }

    return i;
}

What subtlety with fgetc() am I missing here?

尝试在第二个read_flush实现中初始化i

In the second version it looks like you are not initializing i to zero like you do in the first version. So it could be starting with a garbage value larger than count, and thus the loop never executes.

Both versions have the same error. You don't add a NUL on the end of the string. malloc does not initialize the memory that it returns.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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