C language -- super detailed analysis of getchar() function (multi-dimensional analysis, Xiaobai can understand it at a glance!!!)

Table of contents

I. Introduction

2. What is the getchar() function

3. Return type and mechanism of getchar() function 

4. Continuous single string (code demo)

 5. Other uses of the getchar() function, practical exercises (emphasis)

(1) Write the ideal code according to the topic, but there is an unsatisfactory effect 

(2) Reason analysis (detailed explanation of principle)

(3) Solution

 (4) Practice again

5. Advanced practical exercises: enter the password (super key!!!) 

(1) Drill again

 (2) New questions

(3) Solution 

Six, mutual encouragement


I. Introduction

    Before writing this article, I always had a half-understood feeling about these basic functions and didn’t pay much attention 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.

2. What is the getchar() function

getchar()----function to read a single character

Note: At this point, a single character is read

           If you want to read multiple characters use the gets() function

3. Return type and mechanism of getchar() function 

int  getchar (void)

The return type of the getchar() function is int and the integer parameter is void

 At this time, everyone will definitely think, isn't the getchar() function used to input a single character, why is the return type int?

1. What getchar actually returns is the ASCII code value (integer) of the character.
2. When getchar ends or fails to read, it will return EOF.

Note: EOF means end of file, which is essentially -1.

4. Continuous single string (code demo)

#include <stdio.h>
#include <string.h>
int main()
{
	int ch = 0;  //因为 getchar() 返回类型为 int
	while ((ch = getchar()) != EOF) // 连续输入单个字符
	{
		printf("%c",ch);  // 输出一个字符
		//putchar(ch);    // 此时 printf("%c",ch) 与  putchar(ch)  输出结果一样
  	}

	return 0;
}

 Analysis: getchar first reads a character and puts it in ch. If the character is not equal to EOF, it enters the loop and prints the character. When getchar reads to the end of the file or the end, it returns an EOF, which ends the loop.

Note: printf("%c",ch) is the same output as putchar(ch)

Note: If you want to end the continuous input input: ctrl+z

 

 5. Other uses of the getchar() function, practical exercises (emphasis)

 At this point, let's take a look at a classic Niuke example question to see how to use the getchar() function correctly when we usually do the questions

Topic link : Judging whether it is a letter_Niuke Topic_Niuke.com 

Title description: KiKi wants to judge whether the input character is a letter, please help him program it. Please help him write a program to judge whether the input is a letter and the output (is an alphabet.) is not a letter (is not an alphabet.).

(1) Write the ideal code according to the topic, but there is an unsatisfactory effect 

#include<stdio.h>
int main()
{
    char a;
    while ((a = getchar()) != EOF)
    {
        if ((a >= 'a' && a <= 'z') || (a >= 'A' && a <= 'Z'))
            printf("%c is an alphabet.\n", a);
        else
            printf("%c is not an alphabet.\n", a);
    }
    return 0;
}

According to our expectation, if you output a letter, it will output is an alphabet. , if it is not a letter, it will output is not an alphabet. Let me take a look at the running results.

 At this time, everyone will find that it is not the same as we expected. Every time the output is output, there will always be one more is not an alphabet. This will cause a format error when submitting the code. Why is this so? (very headache)

             At this time, do the little friends who are beginners want to smash the computer (at that time, I just shut down and left, haha) 

(2) Reason analysis (detailed explanation of principle)

The principle of the input function:

The scanf() function and getchar() function are included in the input function, they all read our data from the keyboard, but they do not directly read our data from the keyboard. Between them and the keyboard there is an area called the buffer. The input function first checks to see if there is data in the buffer. If there is, it takes it away directly without inputting from the keyboard. If there is nothing in the buffer, it needs to input from the keyboard and then take it away.

Illustration:

 After understanding this principle, let's go back to the previous code and analyze the code diagram again.

a = getchar()

Code: getchar() At this time, enter a character first, for example, enter an A !

Analysis: After the program starts running, there is nothing in the buffer, we can only enter A through the keyboard , in order to let the character A enter the buffer, we actually input   \n unknowingly   , what finally appears in the buffer is  A\ no

Illustration:

At this time, the buffer puts A\n

Note: The getchar() function can only take one character at a time 

while ((a = getchar()) != EOF)

Because it is a continuous input at this time, the first getchar() takes A from the buffer through the input of the keyboard, and the second getcgar() finds that there is a \n in the buffer, which just happens not to need to be input from the keyboard, and takes away the \ n.

 At this time, after analysis, I found that the problem is that the output  is not an alphabet. It is caused by \n.

(3) Solution

At this point, our direction is very clear, we only need to empty the buffer after each input of a character.

At this time, another usage of getchar is used to clear the \n in the buffer.

In the code, you need to add the getchar() function at the beginning of each while() loop to clear each \n.

#include<stdio.h>
int main()
{
    char a;
    while ((a = getchar()) != EOF)
    {
        getchar();
        if ((a >= 'a' && a <= 'z') || (a >= 'A' && a <= 'Z'))
            printf("%c is an alphabet.\n", a);
        else
            printf("%c is not an alphabet.\n", a);
    }
    return 0;
}

 Run the code at this time and find that it finally succeeded.

 (4) Practice again

If you understand my explanation above, you can go to AC by yourself, and there is another question of the same type, you can try it yourself, and feel the thrill of brushing the question!

Topic link: Judging whether it is a vowel or a consonant 

5. Advanced practical exercises: enter the password (super key!!!) 

Topic: Enter a string and judge whether it is the correct password. If it is correct, enter Y, otherwise enter N, and proceed

If the character is judged as Y, output "confirmation successful", otherwise output "confirmation failed".

(1) Drill again

#include<stdio.h>
int main()
{
	char password[20] = { 0 };
	printf("请输入密码:>");
	scanf("%s", password);
	printf("请确认密码(Y/N):>");
	int ch = getchar();
	if (ch == 'Y')
	{
		printf("确认成功\n");
	}
	else
	{
		printf("确认失败\n");
	}
	return 0;
}

 At this point, we will find that we have not entered Y or N, and the confirmation fails and it jumps out.

 At this point, when you see this, you may have seen the problem of this code, which is similar to our previous question ( everyone thinks, this is it??, don’t worry, there are still problems later!!! ) Similarly, I still Analyze it graphically.

scanf("%s", password);

 Enter the password from the keyboard, we enter 123456. In order to put 123456 in, we also hit a carriage return, so the buffer is 123456\n

Next is scanf to read the string in the buffer. The way scanf reads is to read the content before \n , so it reads 123456.

Note: scanf() reads the content before \n

printf("请确认密码(Y/N):>");
	int ch = getchar();

 getchar sees that there is data (\n) in the buffer, and takes it directly without inputting from the keyboard. Naturally, the scene of our running results above appeared: before entering N or Y, the "confirmation failed" popped up immediately.

Similarly, we add getchar() after scanf() input to clear\n 

#include<stdio.h>
int main()
{
	char password[20] = { 0 };
	printf("请输入密码:>");
	scanf("%s", password);
	getchar();//把缓冲区中的\n清理掉
	printf("请确认密码(Y/N):>");
	int ch = getchar();
	if (ch == 'Y')
	{
		printf("确认成功\n");
	}
	else
	{
		printf("确认失败\n");
	}
	return 0;
}

 At this point we will find that we have achieved our expected effect.

 (2) New questions

Did it really achieve the expected effect this time? Of course it didn’t. Otherwise, I would have finished it long ago, and I’m still exhausted. Let’s take a look at the new question.

When we entered the password as 123456 789 (with a space in the middle), before we entered N or Y, the "confirmation failed" popped up immediately.
What's going on here? Let's take a look together

First, there is nothing in the buffer, we need to enter the password 123456 789 through the keyboard

 Note: Then scanf will fetch the data in the buffer, and when it reads a space, it will stop reading (this is a function of scanf). So scanf only took away 123456, and there are (spaces) 789\n left in the buffer.

 further down

getchar();

However, there is only one getchar here, and it can only read one character, that is, only spaces are read , and there are 789\n left in the buffer.

 further down

int ch = getchar();

getchar() takes the 7 in the buffer as soon as it comes , and there is no need for us to enter N or Y from the keyboard. When running, it will automatically jump out of the "confirmation error".

(3) Solution 

We need to clear everything in the buffer first.
Then we use a loop, as long as \n is not read, we always use getchar to read.

//把缓冲区中的内容全读走
	while ( getchar() != '\n')
	{
		;
	}

See the full code:

#include<stdio.h>
int main()
{
	char password[20] = { 0 };
	printf("请输入密码:>");
	scanf("%s", password);
	//把缓冲区中的内容全读走
	while (getchar() != '\n')
	{
		;
	}
	puts(password);  // 验证输入的字符串
	printf("请确认密码(Y/N):>");
	int ch = getchar();
	if (ch == 'Y')
	{
		printf("确认成功\n");
	}
	else
	{
		printf("确认失败\n");
	}

	return 0;
}

 

Test success! ! ! !

Six, mutual encouragement

The following is my understanding of the getchar() function. 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 other functions , please continue to pay attention to me! ! ! ! ! ! ! !  

 

 

Guess you like

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