当前位置:网站首页>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

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 :
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 .
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
边栏推荐
- 关于cmake和gcc的安装的记录
- True thesis of information system project manager in the first half of 2022
- mmdetection之dataset类解读
- Step on the pit. The BigDecimal was improperly used, resulting in P0 accident!
- js手机端复制文本到剪切板代码
- 关于目前CIM(BIM+GIS)行业的一些看法
- Summary of vim common commands
- CodeCraft-22 and Codeforces Round #795 (Div. 2)
- 安装Linux系统的MySQL,在xshell中遇见的问题
- The development of flutter in digital life and the landing practice of Tianyi cloud disk
猜你喜欢

Abbexa 8-OHdG CLIA 试剂盒解决方案

使用Canvas实现的噪音线条h5js特效

js锚点定位可以扩展很多功能

Swin_Transformer源码解读

正斜杠“/”、反斜杠“\、”转义字符“\”、文件路径分割符傻傻记不清楚

Wireshark learning notes (I) common function cases and skills

pwnable start

优惠券的工厂与策略模式实现方案

Step on the pit. The BigDecimal was improperly used, resulting in P0 accident!

用脚本添加URP的RendererData
随机推荐
IIS安装 部署网站
一文带你了解J.U.C的FutureTask、Fork/Join框架和BlockingQueue
This article introduces you to j.u.c's futuretask, fork/join framework and BlockingQueue
Postman-接口测试工具
Abbexa 细菌基因组 DNA 试剂盒介绍
凹印套印原理及影响套印的因素
Linear mobile chess
淘宝短视频避坑指南系列之一--彻底了解淘宝短视频
美学心得(第二百三十七集) 罗国正
How to locate the hot problem of the game
Record of cmake and GCC installation
高数_第6章无穷级数__绝对收敛_条件收敛
JS special effect of canvas divergent particle H5 animation
if else的使用太简单?(看懂这篇你的逻辑会进一步提升)
LeetCode树经典题目(一)
Some views on the current CIM (bim+gis) industry
苹果放大招!这件事干的太漂亮了……
小程序积分商城如何实现营销目的
Chunk extend: hit training lab13
ZigBee模块无线传输星形拓扑组网结构简介