scanf() function--continuous output (understand in seconds, super detailed!!!!)

Table of contents

I. Introduction

Two, three kinds of continuous input in C language

(1)while(~scanf("%d %d",&a,&b)) 

常用(2)while(scanf("%d %d", &a, &b)!=EOF) 

Key point (3) while(scanf("%d",&m)==1)

Three, mutual encouragement 


I. Introduction

    Before writing this article, I always had a half-understood feeling about these basic functions and didn’t care too much until I encountered a full screen of hot hot hot hot hot hot hot hot hot hot hot hot hot hot hot Hot times or just input characters always do not meet the format requirements of the topic . So far, I have read some articles by big guys and made what I have to understand. 

Two, three kinds of continuous input in C language

(1)while(~scanf("%d %d",&a,&b)) 

At this time, you need to understand the source code, complement code, and inverse code. Brothers who need it can read my previous article:

http://t.csdn.cn/qTWS9

~ is a bitwise inversion, the hexadecimal complement of -1 is represented as 0xffffffff, f is binary 1111, all become 0 after inversion, so while ends, and only when the return value is EOF (ie -1) , its negated value is 0, and the while loop can end.

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

常用(2)while(scanf("%d %d", &a, &b)!=EOF) 

    You can input infinitely until the end of the input is EOF

#include <stdio.h>
#include <string.h>
int main()
{
	int a, b;
	while (scanf("%d %d", &a, &b)!=EOF)
	{
		printf("%d\n", a + b);
	}
	return 0;
}

Key point (3) while(scanf("%d",&m)==1)

    while(scanf("%d",&m)==1) is to input countless numbers continuously .

    Among them, the number of inputs is related to the scanf function . For example:

    while(scanf("%d %d",&m,&n)==2) You can also enter 2 numbers continuously

    Key point: It is convenient to add restrictions in while, which is more convenient when doing questions

   For example: the question requires continuous input of a number, but this number cannot be 0

   while(scanf("%d",&m)==1 && m!=0)  will do

#include <stdio.h>
#include <string.h>
int main()
{
	int a;
	int b[5] = { 0 };
	int x = 0;
	while (scanf("%d", &a) == 1 && a != 0) // 1 2 0 4 5
	{
		b[x++] = a;
	}
	for (int i = 0; i < 5; i++)
	{
		printf("%d ", b[i]);     // 1 2 0 0 0
	}
	return 0;
}

Three, mutual encouragement 

    The following is my understanding of the continuous input of scanf(). If there are friends who don’t understand or find problems, please tell them in the comment area. At the same time, I will continue to update my understanding of the getchar() function. Please continue to pay attention to me. ! ! ! ! ! ! !

Guess you like

Origin blog.csdn.net/weixin_45031801/article/details/127233459