Categories:
.NET (357)
C (330)
C++ (183)
CSS (84)
DBA (2)
General (7)
HTML (4)
Java (574)
JavaScript (106)
JSP (66)
Oracle (114)
Perl (46)
Perl (1)
PHP (1)
PL/SQL (1)
RSS (51)
Software QA (13)
SQL Server (1)
Windows (1)
XHTML (173)
Other Resources:
When I read numbers from the keyboard with scanf ...
When I read numbers from the keyboard with scanf and a "%d\n" format, like this:
int n;
scanf("%d\n", &n);
printf("you typed %d\n", n);
it seems to hang until I type one extra line of input.
✍: Guest
Perhaps surprisingly, \n in a scanf format string does not mean to expect a newline, but rather to read and discard characters as long as each is a whitespace character. (In fact, any whitespace character in a scanf format string means to read and discard whitespace characters.Furthermore, formats like %d also discard leading whitespace, so you usually don't need explicit whitespace in scanf format strings at all.)
The \n in "%d\n" therefore causes scanf to read characters until it finds a non-whitespace character, and it may need to read another line before it can find that non-whitespace character. In this case, the fix is just to use "%d", without the \n (athough your program may then need to skip over the unread newline;scanf was designed for free-format input, which is seldom what you want when reading from the keyboard. By ``free format'' we mean that scanf does not treat newlines differently from other whitespace. The format "%d %d %d" would be equally happy reading the input
1 2 3
or
1
2
3
(By way of comparison, source code in languages like C, Pascal, and LISP is free-format, while traditional BASIC and FORTRAN are not.)
If you're insistent, scanf can be told to match a newline, using the ``scanset'' directive:
scanf("%d%*[\n]", &n);
Scansets, though powerful, won't solve all scanf problems,
2015-10-23, 950👍, 0💬
Popular Posts:
What are the five levels in CMMI? There are five levels of the CMM. According to the SEI, Level 1 – ...
What are the types of variables x, y, y and u defined in the following code? #define Atype int* type...
How To Merge Cells in a Column? - XHTML 1.0 Tutorials - Understanding Tables and Table Cells If you ...
The following variable is available in file1.c, who can access it? static int average; Answer: all t...
How To View All Columns in an Existing Table? - Oracle DBA FAQ - Managing Oracle Database Tables If ...