0

I was testing one of simple getchar() function on GNU compiler, but why not get expected output

mto@ubuntu:~/c$ ./a.out 
agc

mto@ubuntu:~/c$

code as following :

#include <string.h>
#include "stdio.h"
#define MAX 80
int main()
  {
        char  ch, buffer[MAX+1];
        int x=0 ;
        while ((ch =getchar() != '\n') && x<MAX)
                buffer[x++]= ch;
         buffer[x]= '\0';

 int len = strlen(buffer);

for (int c=0; c< len; c++)
       printf("%c" , buffer[c]);
       return 0;

}
2
  • Please format your code consistently before asking people to look at it. Commented Oct 9, 2017 at 16:21
  • 2
    This (ch = getchar() != '\n') should be (ch = getchar()) != '\n'. You assign the result of the comparison to ch, but you want to assign the character. Commented Oct 9, 2017 at 16:25

1 Answer 1

2
while ((ch =getchar() != '\n') && x<MAX)

should be

while (((ch = getchar()) != '\n') && x<MAX)

Notice the extra ( .. ) around the assignment. ch =getchar() != '\n' is equivalent to and evaluated as ch = (getchar() != '\n') due to operator precedence. != has higher precedence than =(assignment).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.