ProgrammingHardProduct company OA
After `scanf("%d", &n);` reads the input 42 followed by Enter, why does the next getchar() return '\n' instead of waiting for new input?
- A. %d stores the newline in n along with 42
- B. scanf always appends a newline to its input
- C. getchar reads from a different stream than scanf
- D. %d stops at the newline and leaves it unread in the input buffer
Correct answer: D. %d stops at the newline and leaves it unread in the input buffer
Conversions like %d skip leading white space but stop at the first character that cannot be part of the number, leaving it unread. The leftover '\n' is the next character available. A space in the format (" %c") or a loop that discards up to '\n' fixes it.
More C Programming questions
- What is printed? c int buf[4], head = 0, count = 0; for (int v = 1; v <= 6; v++) { buf[(head + count) % 4] = v; if (count < 4) count++…
- What is printed? c int st[10], top = -1; #define PUSH(x) (st[++top] = (x)) #define POP() (st[top--]) int main(void) { PUSH(3); PUSH(5)…
- A binary tree is stored with child indices (−1 for none). What does h(0) return? c int L[] = {1, 3, -1, -1, -1}, R[] = {2, 4, -1, -1, -1}…
- With the tree below, what does in(0) print? c char key[] = "ABCDE"; int L[] = {1, 3, -1, -1, -1}, R[] = {2, 4, -1, -1, -1}; void in(int n)…
- What is wrong with this code? c char s = malloc(5); strcpy(s, "hello");
- With 4-byte int, what is printed? c int a[3] = {7, 8, 9}; int (p)[3] = &a; printf("%d %d %zu", (p)[1], p + 1, sizeof p);