How to analyze the input in the while condition?

Asked

Viewed 132 times

1

I am learning C, and as the language in which I was "literate" is Python, I usually make associations to better assimilate.

In Python, I can receive a direct value in the while condition. Ex.:

while int(input()) != 0:
    faça isso

It is also possible (in Python and C) to declare a varive before while, receive a new value at the end of each loop and then parse. Ex (in Python).:

n = 1
while n != 0:
    faça isso

    n = int(input)

But I was wondering if you have any way of doing like in the first example, but in C.

I tried it as follows (in C):

int n;

while(scanf("%d", &n) != 0){
    faça isso
}

But it runs the loop even if I type 0.

Thanks in advance.

  • 1

    Have you tried while(scanf("%d", &n) && n != 0) ?

2 answers

1


When you perform scanf("%d", &n) it will store the read value in the address n. Logo just add && n != 0 to analyze the input.

int n;
while(scanf("%d", &n) && n != 0){
  printf("Não é zero! :)\n");
}
printf("Ops :(\n");

Example working on repl it..

  • 1

    The scanf returns the amount of variables read, so if you reach the end of the input it will come out of the loop. Interesting approach

  • Thank you very much. That’s exactly what I was looking for. Thanks!

0

Just add the "&&" in between scanf("%d", &n) and the n != 0 for the compiler to analyze both conditions. Being as follows:

int n;

while(scanf("%d", &n) && n != 0) {
  faca tal coisa;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.