C language #getchar () function

Source: Internet
Author: User

1, the role of GetChar ()

The GetChar () function is to read data from a buffer into a character, the first time the data is read GetChar () will wait for the user to type enter and start reading from the buffer, if the buffer data is greater than 1 bytes, the remaining data is temporarily stored in the buffer, The getchar reads sequentially, without requiring the user to enter enter again to trigger the read.

The return value of GetChar () is an integral type of data whose value corresponds to the ASCII code of the character.

2, statistics input blank number of small program

  

1#include <stdio.h>2 3 Main () {4     5     intN;6     intm;7n =0;8printf"Please input a string:\n");9 Ten      while((M = GetChar ())! ='\ n'){ One         if(M = =' '){ A++N; -         }     -     } theprintf"n =%d\n", n); -      -}

The program realizes the simple function of statistic space and assigns the data read by GetChar () to the integer variable m for counting the number of spaces.

Q1: In c language, char variable is essentially an integer variable, and if M is defined as char data in the program, can the function be implemented?

Q2: What happens when you change the wording?

Program into the dead loop, why?

1#include <stdio.h>2 3 Main () {4     5     intN;6     intm;7n =0;8printf"Please input a string:\n");9m =GetChar ();Ten      while(M! ='\ n'){ One         if(M = =' '){ A++N; -         }     -     } theprintf"n =%d\n", N);  -      -}

A1: can achieve

A2: The first way GetChar () reads only one character outside of the loop (when the character being read is not entered in the loop), after entering the loop no longer runs GetChar () reads the external characters, the value of M is not changed, of course, the dead loop;
The second each cycle runs once GetChar () reads a character until the input carriage ends;

C language #getchar () function

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.