Search code examples
cstreamgetchar

how to get the left character in stream?


Here is the function definition of get_line which:-

  1. skip whitespaces in the begining.

  2. stop at first white space.

  3. stop at first newline character and place it in the array.
  4. leave behind character if it does not have space available.

int get_line (char* ch, int n)
{

    if ( n <= 0)
        return 0;

    char c;

    while ( isspace(c = getchar()));
    int i = 0;

    do {
        ch[i++] = c;
        if ( i == n)
            break;
    }while ( ! isspace(c = getchar()));

    if ( c == '\n')
        ch[i++] = '\n';

    ch[i] = '\0';
    return i;
}

int main()
{

    char array[5];

    get_line(array, 4);
    printf("%s", array);

    char c;

    while ( (c = getchar()) != '\n'){
        printf("\n%c", c);
    }
    return 0;
}

But when i enter more characters then the size and try to print the remaining character in main using the last while loop, it prints weird characters and not printing the remaining characters in the stream as required by the fourth specification of the function. Please tell me why this is happening?


Solution

  • It looks like you ran afoul of operator precedence.

    In this statement:

    while ( c = getchar() != '\n'){
    

    The comparison operator != has higher precedence than the assignment operator =. So getchar() != '\n' is evaluated first and will be either 1 or 0 since it is a boolean expression.

    Assuming the next character is not a newline, the value will be 1. Then c = 1 is evaluated and the loop continues by printing the value 1 as a char. When a newline is found, getchar() != '\n' evaluates to 0, then c = 0 is evaluated and the loop exits.

    You need to add parenthesis here to get the intended order of operations:

    while ( (c = getchar()) != '\n'){