Scanf error points

Source: Internet
Author: User

Scanf is easy to troubleshoot. 1. Return key is also obtained. Example: char a; while (1) {scanf ("% c", & a); printf ("getchar: % d \ n ", (int) a);} enter: 1234 result: get char: 49 // 1get char: 50 // 2get char: 51 // 3get char: 52 // 4get char: 10 // \ n (line feed) [parsing: scanf gets characters one by one. When you enter 1234 and a enter key, a total of five characters, obtain these five characters respectively. 2. Strictly match the scanf ("1123% s", & str) string. [str is aaabb when 1123aaabb is input. However, when 24aabbdd is input, error occurs, because 1123 is required.] 3. Avoid the case where the carriage return is automatically obtained. For example: char a, B; scanf ("% c", & a); scanf ("% c ", & B); // scanf (" % C ", & B); printf (" a = 0x % d \ nb = 0x % d \ n ", (int) a, (int) B); input: enter 1 and press Enter. Result: a = 0x49b = 0x10 [resolution: the reason is that a has taken 1, and B has taken \ n % c, there must be a space before it, otherwise, the system will read the carriage return that you typed after entering another value into this variable, resulting in an endless loop. Of course, if scanf ("% c", & B) is the first read statement, no space is required.] 4. Read string size limitation example: char * p, str [20]; scanf ("10% s", p); scanf ("% s", str); [resolution: once the number of input characters is greater than 10, p will not continue to be read, and the next reading function is scanf ("% s", str) will start to read from 11th characters.] 5. Clear the Keyboard Buffer fflush (stdin); [resolution: Clear the Keyboard Buffer]

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.