Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getchar() keeps returning 1

Tags:

c

getchar

i am new to StackOverflow. I hope to be able to learn a lot here. So, i'm a beginner in C. I'm just trying a few things, like using very basic functions. Here's my code:

#include <stdio.h>
#include <stdlib.h>


int main()
{   int c;
    int i,wl[20];
    int count = 0;
   i = 0;

printf("Insert line: ");    


while(c= getchar() != '\n'&& c != EOF)
    printf("integer value of the variable is %d\n", c);
return 0;
}

This should be an easy program: you insert an input and gives you the current value in int. The problem is: getchar keeps returning 1, no matter what. enter image description here

Also, i have another question. I know that char in C is basically an 8 bit integer and as a matter of fact you can using char and int (with some problems, as integer are not 8 bit variables) interchangeably. So: why do some people declare a variable as int instead of char when in need to store a char with getchar? Sorry for such basic questions.

N.B: other variables are declared as this is part of a bigger code. all the other parts of the code were put as code in order to test this (/* */). Sorry for my English, i hope what i wrote is clear.

like image 633
Emanuele Monea Avatar asked Dec 09 '25 21:12

Emanuele Monea


1 Answers

This:

c= getchar() != '\n'

is equivalent to

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

so not at all what you meant. So the 1 is the result of the != comparison. You need

(c = getchar()) != '\n'
like image 159
unwind Avatar answered Dec 12 '25 12:12

unwind



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!