Techniques for using scanf in a while statement in C language

Source: Internet
Author: User
Tags bitwise

Today, my friend and I discussed a piece of code, is a HDU OJ on the purpose of the solution, the code is as follows

#include <stdio.h>{    int a ,    b;  while (~SCANF ("%d%d",&a,&b))    {        printf ("%d\n", A +b)    ;    } return 0 ;}

At first, I thought the bitwise negation operator in the while statement in the code was wrong and should be a logical non-operator.

Then I found a similar question on the Quora, and I modified and translated one of the answers:

Refer to the man manual for the scanf function for a description of the return value as follows

The function returns the number of entries that have been successfully matched and read in the format, and may return a number less than the total number of entries, and may even return 0 in the case of a match failure.

If an input end signal is received before the first successful read or a matching error occurs, EOF will be returned. EOF is also returned when a read-in error is encountered.

In the above code, the return value of scanf may be 0,1,2 or EOF.

The bitwise inverse of the 0,1,2 is a non-0 value, at which time the while loop continues execution.

In most environments, EOF is defined as a constant with a value of 1, and a value of 0 is obtained after a bitwise inversion. The while loop will now end.

In summary, the while statement can continuously read data from the input stream until the input stream ends and the loop ends.

It is worth mentioning that this usage is only valid in the context where EOF is defined as-1, and is very poor in readability. So you should try to avoid using it.

In Linux and OS X, you can send an input end signal via ctrl+d, and you'll need to use CTRL + Z in Windows.

Resources:

The answer on the Quora

SCANF (3)

Techniques for using scanf in a while statement in C language

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.