Search code examples
cstdin

Function to read line from standard input in C not working as expected


This function is supposed to get a line from the terminal. But it doesn't! I have gone over the code multiple times, but I haven't been able to pinpoint the problem! Please help! It doesn't seem that the code is entering the while block.

int getline(char line[]) {
int i = 0 ;
int c ; 
while( ((c=getchar()) != EOF) && (c =! '\n') ) { 
    line[i++] = c ;
}
line[i] = '\0' ; 
return i ; 
}

Solution

  • Well this is incorrect

    while( ((c=getchar()) != EOF) && (c =! '\n') )
    

    it should be

    while( ((c=getchar()) != EOF) && (c != '\n') )
    

    Do you notice the difference? != is comparison (which is correct), and =! is completely different (which means negating '\n' and assign it to c) - which was wrong. So, attentions to the details please :)