Ramy Al Zuhouri
Ramy Al Zuhouri

Reputation: 21996

Linux non deterministic behaviour taking input

I have written this function:

char* input(char* buffer, FILE* fp)
{
    char* result=fgets(buffer,LMAX,fp);
    if(result!=NULL)
    {
    const unsigned int length=strlen(buffer);
    if(buffer[length-1]=='\n')
        buffer[length-1]='\0';
    }
    return result;
}

It just takes in input a line of text if fp is equal to stdin.
I have used it many times and it works.
I take the result of fgets just in the case fp is a FILE pointer, so I have to check that the result is not NULL in the case the stream is not good for input operations.
The problem is that if I use it this way:

char buffer[LMAX];  // LMAX = 100, defined constant
input(buffer,stdin);
puts(buffer);

If the input is like "#dest :a", the puts prints "#dest", cutting the rest of the string.The big problem is that this function was working and one hour ago (it was identical) if I did take in input a string like "#dest :a" the puts was printing "#dest :a".And nothing has changed.Also if I try debugging and I write this:

char* input(char* buffer, FILE* fp)
{
    char* result=fgets(buffer,LMAX,fp);
    puts(buffer);  //prints always "#dest :a"
    if(result!=NULL)
    {
    const unsigned int length=strlen(buffer);
    if(buffer[length-1]=='\n')
        buffer[length-1]='\0';
    }
    return result;
}

The problem is that in the function it prints "#dest :a".
This function sometimes works and sometimes not, I'm K.O., I can't stand a non deterministic behaviour, what could be this problem (and probably a bug) dued to?

Upvotes: 2

Views: 152

Answers (1)

timkd127
timkd127

Reputation: 71

I ran your code several times and Im getting nothing but correct output so i cant reproduce the problem. I do think I know what the issues is. try calling

    flush(stdin);

before your call to input.

Upvotes: 1

Related Questions