Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use getchar () in C language

2025-03-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

Editor to share with you how to use getchar () in C language, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's learn about it!

I. the working principle and function of getchar () series 1.getchar ()

How it works: getchar () is a library function in stdio.h, its function is to read a character from the stdin stream, that is, if stdin has data, it can be read directly without entering it, the first time getchar () does require manual input, but if you type multiple characters, later getchar () will be read directly from the buffer when it is executed.

It's actually the input device-> memory buffer-> getchar ()

The key you press is put in the buffer, and then it is supplied to the program getchar ()

Have you ever tried to hold down a lot of keys and then tick after a while, but the buffer is full and the key you press behind is not saved in the buffer?

All the characters entered by the keyboard are stored in the buffer. Once you type enter, getchar enters the buffer to read the characters, returning only the first character as the value of the getchar function at a time. If there is a loop or enough getchar statements, all the characters in the buffer will be read out in turn until'\ n'. To understand this, the series of characters you enter are read out in turn because the loop allows you to repeatedly use getchar to read characters in the buffer, rather than getchar can read multiple characters, in fact, getchar can only read one character at a time. If you need to cancel the influence of'\ n', you can use getchar (); to clear, here getchar (); just get'\ n 'but not assigned to any character variable, so there will be no effect, which is equivalent to clearing the character.

Function 1: read a character from the buffer, which is equivalent to clearing the buffer.

Function 2: the front scanf () will leave a character'\ n'in the buffer when reading the input (caused by pressing the enter key after typing), so if you don't add a getchar () here to take away the carriage return, the next scanf () will not wait for characters to be typed from the keyboard, but will directly take away the "useless" carriage return, resulting in reading errors.

two。 Use getchar () to clean the carriage return\ n

This question is reproduced from n_s_X14, but the author left a question at the end of the article, and now I'm here to explain why.

The source code of the article is:

# include int main (void) {char m [40]; char n; printf ("please input first str:\ n"); / / prompt the user for the first string scanf ("% s", m); / / get the user's first input string printf ("you input str is:% s\ n", m) / / output the first string printf of the user's input ("input second char:\ n"); / / prompt the user for the second character scanf ("% c", & n); / / get the user's second character printf ("now you input second char is:% c\ n", n); / / output the second character return 0;}

Output:

Please input first str:

Abc

You input str is: abc

Input second char:

Now you input second char is:

Program ended with exit code: 0

Problem: the first time we typed abc, we successfully printed out you input str is: abc, but executed to printf ("input second char:\ n"); before we could wait for the second input. Why is that?

Reason:

In fact, when we typed and pressed enter for the first time, the console got a total of four characters, namely: a, b, c, enter (enter). However, because the scanf () method ends fetching from the console when it encounters non-characters, after entering 'abc', press' enter', the value of 'abc'' is assigned as a string to the'm 'array of type' char'', and the resulting string: 'enter' is saved in the buffer entered by the console. Then proceed to the next piece of output code, and then ask the user for input. At this point, because the last used string is saved in the buffer, the scanf () method now fetches the last used string from the console buffer and intercepts only the first character: 'enter (enter)' before the console buffer is finished. So in the input that seems to have been skipped, the scanf () method has already obtained our input, which is a 'enter'.

Resolve the problem:

Using the getchar () method, clear the cache behind the abc (enter enter).

# include int main (void) {char m [40]; char n; printf ("please input first str:\ n"); / / prompt the user for the first string scanf ("% s", m); / / get the user's first input string printf ("you input str is:% s\ n", m) / / output the first string of the user's input getchar (); printf ("input second char:\ n"); / / prompt the user for the second character scanf ("% c", & n); / / get the user's second character printf ("now you input second char is:% c\ n", n) / / output the second character entered by the user, return 0;}

Output:

Please input first str:

Abc

You input str is: abc

Input second char:

De

Now you input second char is: d

Program ended with exit code: 0

3. Use getchar () to clean up the cache

At the end of the article, there is a problem: if you enter ab for the first time, add a space and enter, the original problem will occur again, that is, the program will automatically skip the exit between the next input after only outputting ab, and the console output is shown in the following figure.

Reason:

When getting the user's first input string, scanf ("% s", & m);, we use% s as the conversion description. The function of% s is to "interpret the input as a string. All characters from the first non-white space character to the next white space character are input." So scanf understands the input ab space + carriage return as ab+ carriage return (there is no space after ab), but it is still stored in the cache in the form of ab space + carriage return. We enter ab space + enter, which is stored in the cache as follows:

Among them, the third box is the space bar.

When the program finishes running getchar ();, only the space bar in the third box is cleared because getchar () is executed at a time; only one cache is cleared, leaving the enter key in the fourth box, so the same problem occurs again.

Solve the problem: that means you only need to run getchar () twice; clear the third and fourth frames and it will be fine.

# include int main (void) {char m [40]; char n; printf ("please input first str:\ n"); / / prompt the user for the first string scanf ("% s", m); / / get the user's first input string printf ("you input str is:% s\ n", m) / / output the first string getchar () of the user's input; / / clear cache getchar () for the first time; / / clear cache printf for the second time ("input second char:\ n") / / prompt the user for the second character scanf ("% c", & n); / / get the user's second character printf ("now you input second char is:% c\ n", n); / / output the second character return 0;}

Output:

Thus, when we enter ab space + enter for the first time, the program runs normally.

Further: if we enter a space b + enter, scanf ("% s", m); this step can only be read to a, because an is followed by a space. But a space b + carriage return is stored in the buffer like this:

Therefore, if you want the program to work properly, you need to add getchar () three times after the first string of the output user's input; that is, delete the contents of the second, third, and fourth frames.

Question: if we enter a space bbbbbbbb+ enter, it may take countless getchar (); to clear the cache, what should we do?

Solution: join the while loop while (getchar ()! ='\ n') continue

# include int main (void) {char m [40]; char n; printf ("please input first str:\ n"); / / prompt the user for the first string scanf ("% s", m); / / get the user's first input string printf ("you input str is:% s\ n", m) / / output the first string while (getchar ()! ='\ n') of the user's input / / delete the cache continue; printf ("input second char:\ n") through the while loop; / / prompt the user for the second character scanf ("% c", & n) / / get the user's second character printf ("now you input second char is:% c\ n", n); / / output the second character return 0;} entered by the user

At this point, we enter a space bbbbbbbb+ and enter, and the program runs normally.

Parsing:

While (getchar ()! ='\ n') continue

You can see that this code replaces countless getchar (), and its function is to skip the rest of the input lines

The first while loop eliminates the second cache, and the second while cycle eliminates the third cache. Until the eighth time. Again for the last time, getchar () also eliminates carriage returns.

While (getchar ()! ='\ n') can be split into two steps

The first step calls the getchar () method (here getchar (); just gets'\ n 'but doesn't assign any character variables, so it doesn't matter, which is equivalent to clearing the character).

The second step is to determine whether the acquired cache is equal to'\ n'.

4. Mix scanf () with getchar ()

Suppose the program requires getchar () to handle character input and scanf () to handle numeric input. Both functions can complete the task well, but they cannot be mixed. Because getchar () reads every character, including spaces, tabs, and line feeds, while scanf () skips spaces, tabs, and line feeds when reading numbers.

Example:

The user is required to enter a letter and two numbers, and output a series with the first number as the number of rows, the second number as the number of columns, and letters as the content, and you can enter continuously until you type enter to exit the program:

# include void display (char cr,int lines,int width); int main (int argc, const char * argv []) {int ch; int rows,cols; printf ("Enter a character and two integers:\ n"); while ((ch=getchar ())! ='\ n') {scanf ("% d% d", & rows,&cols); display (ch, rows,cols); printf ("Enter another character and two integers;\ n") Printf ("Enter a newline to quit.\ n");} printf ("Bye.\ n"); return 0;} void display (char cr,int lines,int width) {int row,col; for (row=1; row)

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report