当前位置:网站首页>C language -- 13 loop statement while

C language -- 13 loop statement while

2022-06-10 18:15:00 Try!

Before learning and reviewing this knowledge , Have mastered if Structure and usage of statements .

if ( Conditions )
	 sentence ;

When the conditions are met ,if Statement execution in the structure , And only once ; If the conditions are not met, the execution will not be carried out . But in life, one thing needs to be done many times , That's where it comes in while Statement to implement the loop .

1、while Sentence structure

while ( expression )
	 Loop statement ;

Example : Printing with circular structure 1-10

#include <stdio.h>
int main()
{
    
	int i = 0;
	while(i < 10)
	{
    
		i++;
		printf("%d ", i);
	}
	return 0;
}
1 2 3 4 5 6 7 8 9 10

 Insert picture description here
Let's test adding... To the code continue and break What is the result
stay while In circulation ,break Used to permanently terminate a loop

int main()
{
    
	int i = 1; // initialization 
	while (i <= 10) // Judgment part 
	{
    
		if (i == 5)
			break;
		printf("%d ", i);
		i++;   // The adjustment part of the loop variable  
	}
	return 0;
}

The running result is :

1 2 3 4

take break Change it to continue have a look , It is found that the running result is :
 Insert picture description here
Output 4 after , The cursor flashes continuously , Because in while In circulation ,continue The purpose of this is to skip this cycle continue Later code ( So it's over printf("%d ", i);i++; These two sentences ), The direct procedure goes to the judgment part , See if the next cycle .

2、 Code example

Example 1 :
Take a look at what the following code means

int main()
{
    
	int ch = 0;
	while ((ch = getchar()) != EOF)
		putchar(ch);
	return 0;
}

The operation results are as follows :
Input what letter will output what letter , Want to exit the program , Just use the shortcut keys “ctrl + z”.

a
a
A
A
^Z

getchar This means that if the read succeeds , The return is ASCII Code value , If reading fails , Is returned EOF(end of file), Is the end of file flag .
test getchar The function of

int main()
{
    
	int ch = getchar();
	printf("%c\n",ch);
	//putchar(ch);// This statement has the same meaning as the previous one 
	return 0;
}

Run the test code , In the window of printing results , Type in a A Character enter , It will print out A character .(putchar It means to output one character )
stay getchar And the keyboard , Type character “A” It's equivalent to putting “A\n” Into the buffer .
 Insert picture description here
Example 2 :
Suppose you enter a character as a password , Store the password in the string passwd Inside , Then pop up a “ Please confirm the password ” A hint of , If you confirm that the password is correct, type “Y”, Output “ Confirm success ”; Otherwise, type “N”, Output “ Confirmation failed ”. Write the following code :

int main()
{
    
	char passwd[20] = {
     0 };
	printf(" Please input a password :>");
	scanf("%s",passwd);// Suppose the password entered is 2022
	// here passwd The reason for not taking the address is passwd Is an array , The array name of an array is itself an address , therefore 
	// There is no passwd Add the address symbol 
	printf(" Please confirm the password (Y/N):>");
	int ch = getchar();
	if (ch == 'Y')
	{
    
		printf(" Confirm success \n");
	}
	else
	{
    
		printf(" Confirmation failed \n");
	}
	return 0;
}

The result of running this code is as follows :

 Please input a password :>2022
 Please confirm the password (Y/N):> Confirmation failed 

obviously , There is an error in this code . Not waiting for input Y/N, You will be prompted that the confirmation failed . Why is this ? Because we type... On the keyboard “2022” after , You will also type a carriage return , In this case, the buffer will be filled with “2022\n”.
and scanf And getchar It's the input function , They don't take data directly from the keyboard , Instead, it fetches data from the middle buffer , If there is no data in the buffer , It will wait for a bit of information to be input from the keyboard into the buffer .scanf Only those in the buffer will be “2022\n” Inside “2022” take , There are still... In the buffer “\n”;getchar When reading , There is no waiting action , Directly transfer the... In the buffer “\n” Take away , So wait for us to enter Y/N, It's already printed “ Confirmation failed ”.
How to modify the program ?
Will perform scanf In the subsequent buffer “\n” take , That is, clean up the buffer , In this case getchar The function has to wait for input , It can run correctly .
The code is as follows :

int main()
{
    
	char passwd[20] = {
     0 };
	printf(" Please input a password :>");
	scanf("%s",passwd);// Suppose the password entered is 2022
	printf(" Please confirm the password (Y/N):>");
	// Clean buffer 
	getchar();// Handle '\n'
	int ch = getchar();
	if (ch == 'Y')
	{
    
		printf(" Confirm success \n");
	}
	else
	{
    
		printf(" Confirmation failed \n");
	}
	return 0;
}

The running result is :

 Please input a password :>2022
 Please confirm the password (Y/N):>Y
 Confirm success 

At this time, it works correctly for continuous password input , So for discontinuities ( There's a space in the middle ) What about ?
For example, the password is “2022 abc”, The results are as follows :

 Please input a password :>2022 abc
 Please confirm the password (Y/N):> Confirmation failed 

It can be seen that , The program is still flawed . How to deal with it ? This requires cleaning up multiple characters in the buffer . There is only one getchar The function does not handle spaces and “\n” 了 , have access to while loop , Keep it reading , Until will “\n” All read away .

int main()
{
    
	char passwd[20] = {
     0 };
	printf(" Please input a password :>");
	scanf("%s",passwd);// Suppose the password entered is 2022
	printf(" Please confirm the password (Y/N):>");

	 Clean buffer 
	//getchar();// Handle '\n'

	// Clean up multiple characters in the buffer 
	int tmp = 0;
	while ((tmp = getchar()) != '\n')
	{
    
		;
	}
	int ch = getchar();
	if (ch == 'Y')
	{
    
		printf(" Confirm success \n");
	}
	else
	{
    
		printf(" Confirmation failed \n");
	}
	return 0;
}
 Please input a password :>2022 abc
 Please confirm the password (Y/N):>Y
 Confirm success 

Example 3 :

// Only numbers will be printed 
int main()
{
    
	int ch;
	while ((ch = getchar()) != EOF)
	{
    
		if (ch < '0' || ch > '9')
			continue;
		putchar(ch);
	}
	return 0;
}

according to ASCII Code value , We can see that this code means : If it's not a number continue, perform continue Will skip putchar(ch) this sentence , So this code will only print the input numbers in the end , Want to stop running , type “ctrl+z” that will do . The code runs as follows :

1
1
3
3
9
9
^Z
原网站

版权声明
本文为[Try!]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/161/202206101730494961.html