c - how to get the left character in stream? -


here function definition of get_line which:-

  1. skip whitespaces in begining.

  2. stop @ first white space.

  3. stop @ first newline character , place in array.
  4. leave behind character if not have space available.

int get_line (char* ch, int n) {      if ( n <= 0)         return 0;      char c;      while ( isspace(c = getchar()));     int = 0;      {         ch[i++] = c;         if ( == 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 enter more characters size , try print remaining character in main using last while loop, prints weird characters , not printing remaining characters in stream required fourth specification of function. please tell me why happening?

it looks ran afoul of operator precedence.

in statement:

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

the comparison operator != has higher precedence assignment operator =. getchar() != '\n' evaluated first , either 1 or 0 since boolean expression.

assuming next character not newline, value 1. c = 1 evaluated , loop continues printing value 1 char. when newline found, getchar() != '\n' evaluates 0, c = 0 evaluated , loop exits.

you need add parenthesis here intended order of operations:

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

Comments

Popular posts from this blog

searchKeyword not working in AngularJS filter -

sequelize.js - Sequelize: sort by enum cases -

user interface - how to replace an ongoing process of image capture from another process call over the same ImageLabel in python's GUI TKinter -