Comparison of C language getchar(), getch(), scanf() (with C language code)

Comparison of C language getchar(), getch(), scanf() (with C language code)

Recently, I received a question from a child who just started C language about "a series of confused outputs when receiving char type data with scanf() statement", so I rearranged the relevant knowledge points of getchar(), getch(), and scanf() in C language

Let's understand three functions from the life cycle of functions

getchar()

When the function starts running, go to the stdio buffer to see if there are any characters. If there are, get a character and return it to the program. The function ends.

If the stdio buffer is empty, wait for data input from the keyboard, and each character input will be echoed to the screen. Only when the Enter key ('\ n') is pressed, the data including the Enter key before pressing the Enter key will be stored in the stdio buffer, and then getchar() obtains the first character from the stdio buffer and returns it to the program, At the same time, the character pointer of the buffer moves down one bit (that is, the pointer refers to the next character of the obtained character), and the function ends. (Note: getchar() can obtain any character, including line feed key [ASCII code: 10], spacebar [ASCII code: 32], etc.)

code

#include<stdio.h>
int main(void)
{
    int a,b,c;
    printf("please input num a:\n");
    a=getchar();
    printf("please input num b:\n");
    b=getchar();
    printf("please input num c:\n");
	c=getchar();	
    printf("%d,%d,%d",a,b,c);
}

Operation results

please input num a:
1 
please input num b:
please input num c:
2
49,10,50

Interpretation of operation results:

After the program runs and prints "please input num a:", it enters the getchar() function. Since there are no characters in the stdio buffer at this time, the program waits for the user to input from the keyboard;

After entering "1" and pressing enter, the ASCII code of "1" and enter is stored in stdio buffer, and then the getchar() function on line 6 of the program obtains "1" and stores it in variable a. after the function runs, it continues to run

Print out the output content of line 7 and enter the getchar() function of line 8. At this time, the stdio buffer also has a enter key just entered. getchar() directly takes the content of the Enter key and stores it in variable b

Continue to run the print content on line 9 of the program, and then enter the getchar() function on line 10. At this time, the stdio buffer is empty, so you need to wait for the user to input "2" from the keyboard, press enter, and the getchar() function obtains "2" from the Stdio buffer and stores it in variable c

The final printing results are "49", "10" and "50", representing ASCII codes of characters "1", "enter" and "2" respectively.
To achieve the desired results, you can modify the program by adding a getchar() after each character acquisition to obtain the "enter key" attached to each character input in the stdio buffer.
Improved code

#include"stdio.h"
int main(void)
{
    int a,b,c;
    printf("please input num a:\n");
    a=getchar();
	getchar();
    printf("please input num b:\n");
    b=getchar();
	getchar();
    printf("please input num c:\n");
	c=getchar();
	getchar();
    printf("%d,%d,%d\n",a,b,c);
}

Operation results

please input num a:
1
please input num b:
2
please input num c:
3
49,50,51

You can also add fflush(stdin) after each getchar() to empty the stdio buffer, which can achieve the same effect.

Improved code

#include"stdio.h"
int main(void)
{
    int a,b,c;
    printf("please input num a:\n");
    a=getchar();
	fflush(stdin);
    printf("please input num b:\n");
    b=getchar();
	fflush(stdin);
    printf("please input num c:\n");
	c=getchar();
	fflush(stdin);
    printf("%d,%d,%d\n",a,b,c);
}

getch()

The function of getch() directly waits to obtain the characters input from the keyboard and does not echo on the screen, and does not end with the Enter key. Before entering a key, the program obtains the ASCII code of the key and returns, and the function ends.

code

#include "stdio.h"
#include  <conio.h>
int main(void)
{
    int a,b,c;
    printf("please input num a:\n");
    a=getch();	
    printf("please input num b:\n");
    b=getch();
    printf("please input num c:\n");
	c=getch();
    printf("%d,%d,%d\n",a,b,c);
}

Operation results

please input num a:
please input num b:
please input num c:
49,32,50

Interpretation of operation results:

Enter "1", "spacebar" and "2" in sequence. As shown above, the characters entered each time will not be echoed on the screen. Instead of waiting for the Enter key, you can obtain the characters entered by the keyboard, but print out the ASCII code of the input characters.

scanf()

scanf() function is similar to getchar(). First, read characters from stdio buffer. If the buffer has data that meets the format requirements, get the data and return it to the program. The function ends;

If there is no qualified data in the buffer (not necessarily empty here, because sometimes the buffer is not empty, but there is no data in no and format, for example, there is a space in the buffer or enter, but the return type is an integer parameter), wait for the data to be input from the keyboard, and must end with enter, and the input data is stored in stdio buffer, (enter at least one data that meets the format requirements to end the input with enter, otherwise press enter and continue to wait for input) then scnaf() obtains a data from the buffer and returns, and the function ends.

code

#include "stdio.h"
int main(void)
{
    int a,b,c;
    printf("please input num a:\n");
    scanf("%d",&a);
    printf("please input num b:\n");	
    scanf("%d",&b);
    printf("please input num c:\n");
    scanf("%d",&c);	
    printf("%d,%d,%d\n",a,b,c);
}

Operation results

please input num a:

    1  2
please input num b:
please input num c:

        3
1,2,3

Interpretation of operation results:

First, the print content of line 5 of the program is displayed, and then the program executes the scanf() function on line 6. At this time, the stdio buffer is empty, so wait for the user to input from the keyboard;

First, enter a enter key. It is found that the function does not end and continues to wait for input. This means that at least one data meeting the scanf() format requirements must be input before the Enter key ends input;

Then enter "1" after entering several spaces, then enter two spaces, press the key and enter "2", and then press enter to end the input;

Then, the scanf() function in line 6 obtains "1" and stores it in variable a;

Then, the program executes the print content of line 7. It is found that line 8 does not seem to be executed, and the content of line 9 is directly printed. Here, in fact, scanf() in line 8 has been executed, because there is still an input data "2" in stdio buffer, and scanf() in line 8 directly reads "2" from the buffer and stores it in variable b without waiting for the user to input from the keyboard;

Then the program executes the print content in line 9, and then executes the scanf() function in line 10. At this time, stdio does not meet the format data, so you need to wait for the user to input from the keyboard. Here, first enter the Enter key and several space keys, then enter "3", and then enter the Enter key. Scanf() obtains "3" and stores it in variable c;

Finally, print the results of variables a, b and c in integer form: 1, 2 and 3

It should be pointed out here that when the scanf () function fetches data from stdio buffer, it will clear all characters before finding the data required by no and format. In fact, it is to move the pointer to the next bit of the obtained data. The test program is as follows

code

#include "stdio.h"
int main(void)
{
    int a,b,c;
    printf("please input num a:\n");
    scanf("%d",&a);
	printf("getchar():%d\n",getchar());
    printf("please input num b:\n");	
    scanf("%d",&b);
    printf("please input num c:\n");	
    scanf("%d",&c);	
    printf("%d,%d,%d",a,b,c);
}

Operation results

please input num a:

    1  2
getchar():32
please input num b:
please input num c:

        3
1,2,3

Interpretation of operation results:

getchar() is added between the first two scanf(), the value obtained is 32, that is, the ASCII code of the space, so it obtains the space entered between "1" and "2", but the Enter key before "1" is not obtained, indicating that it has been taken from the stdio buffer by the first scanf() function, or it is understood that the pointer has pointed to the address after "1"

About scanf() getting characters

Test code

#include "stdio.h"
int main(void)
{
    char a,b,c;
    printf("please input num a:\n");
    scanf("%c",&a);
    printf("please input num b:\n");
    scanf("%c",&b);
    printf("please input num c:\n");
    scanf("%c",&c);
    printf("%c,%c,%c\n",a,b,c);
}

Operation results

please input num a:
a
please input num b:
please input num c:
b
a,
,b

Interpretation of operation results:

After entering a, press enter to directly run the printed contents of lines 7 and 9. It seems that line 8 does not run;

In fact, like the getchar() function, press enter after entering a, and a and enter enter together into the stdio buffer;

In line 6, the scanf() function obtains the character a from the buffer and stores it in the a variable, and then executes line 7. When executing line 8, because there is a enter key in the buffer, the scanf() function obtains the Enter key and stores it in the variable b, so there is no need to wait for user input and directly enter line 9 for printing;

After that, the program in line 10 finds that there is no data in the buffer, so it needs to be input by the user. Here, enter "b" to store the variable c, and then print the variables a, b and c in turn. It can be seen that "a" is output first, then line feed, and then "b"

For improvement, you can also use getchar() to get the Enter key that must be entered after entering the data, or use fflush(stdin) to empty the buffer

Children's problems

code

#include <stdio.h>
// 1,2
// 1.2,3.4
// 666666,888888
// 123,456
// A,a
int main(void)
{
   int nA,nB;
   float fC,fD;
   long lE,lF;
   unsigned int u,v;
   char ch1,ch2,ch3,ch4,ch5,ch6;
   scanf("%d,%d",&nA,&nB);
   scanf("%f,%f",&fC,&fD);
   scanf("%ld,%ld",&lE,&lF);
   scanf("%o,%o",&u,&v);
   scanf("%c,%c,%c,%c,%c,%c",&ch1,&ch2,&ch3,&ch4,&ch5,&ch6);
   printf("\n");
   printf("a=%7d,b=%7d\n",nA,nB);
   printf("c=%10.2f,d=%10.2f\n",fC,fD);
   printf("e=%17ld,f=%17ld\n",lE,lF);
   printf("u=%o,v=%o\n",u,v);
   printf("c1=%c,c2=%c,c3=%c,c4=%c,c5=%c,c6=%c\n",ch1,ch2,ch3,ch4,ch5,ch6);
   return 0;
}

Operation results

1,2
1.2,3.4
666666,888888
123,456
A,a,B,b,C,c

a=      1,b=      2
c=      1.20,d=      3.40
e=           666666,f=           888888
u=123,v=456
c1=
,c2=,c3=,c4=,c5=,c6=

Question:

Why does the output of ch1, CH2, CH3, CH4, CH5 and ch6 on line 24 of the program not meet the expectations?

Problem analysis:

When the program executes the code in line 17, the user presses the Enter key after entering 123456. At this time, 123456 and the Enter key enter the stdio buffer together. On line 17, the scanf() function obtains the characters 123456 from the buffer and stores them in U and V variables respectively, and then executes the code in line 18, because there is a enter key in the buffer, scanf() The function obtains the Enter key and stores it in the variable ch1. At the same time, because the Enter key is read, the next line code ends and the subsequent code starts to execute. Therefore, only the Enter key is obtained and stored in the character variable ch1, while CH2, CH3, CH4, CH5 and ch6 are not stored in any value (i.e. null value)

Suggestions for improvement:
You can use getchar() to get the Enter key that must be entered after entering the data

Improved code

#include <stdio.h>
int main(void)
{
   int nA,nB;
   float fC,fD;
   long lE,lF;
   unsigned int u,v;
   char ch1,ch2,ch3,ch4,ch5,ch6;
   scanf("%d,%d",&nA,&nB);
   scanf("%f,%f",&fC,&fD);
   scanf("%ld,%ld",&lE,&lF);
   scanf("%o,%o",&u,&v);
   getchar();
   scanf("%c,%c,%c,%c,%c,%c",&ch1,&ch2,&ch3,&ch4,&ch5,&ch6);
   printf("\n");
   printf("a=%7d,b=%7d\n",nA,nB);
   printf("c=%10.2f,d=%10.2f\n",fC,fD);
   printf("e=%17ld,f=%17ld\n",lE,lF);
   printf("u=%o,v=%o\n",u,v);
   printf("c1=%c,c2=%c,c3=%c,c4=%c,c5=%c,c6=%c\n",ch1,ch2,ch3,ch4,ch5,ch6);
   return 0;
}

Operation results

1,2
1.2,3.4
666666,888888
123,456
A,a,B,b,C,c

a=      1,b=      2
c=      1.20,d=      3.40
e=           666666,f=           888888
u=123,v=456
c1=A,c2=a,c3=B,c4=b,c5=C,c6=c

Due to my limited ability, please criticize and correct me if there is any misunderstanding or description
Email: 517093978@qq.com

Tags: C Code Style

Posted on Wed, 06 Oct 2021 21:00:11 -0400 by muthuraj_mr