ProgrammingHardProduct company OA
The user types hello and presses Enter. After `char buf[8]; fgets(buf, sizeof buf, stdin);`, what does buf hold?
- A. Only "hel", because fgets reads sizeof buf / 2 characters
- B. "hello": the newline is discarded
- C. "hello\n": the newline is kept, followed by '\0'
- D. "hello\n" with no terminating '\0'
Correct answer: C. "hello\n": the newline is kept, followed by '\0'
fgets reads up to sizeof buf − 1 characters, stopping after a newline, which it stores, and always adds '\0'. That kept '\n' is why code often strips it with buf[strcspn(buf, "\n")] = '\0'.
More C Programming questions
- The user types abcdefghij and presses Enter. What is strlen(buf) after char buf[8]; fgets(buf, sizeof buf, stdin);?
- After scanf("%d", &n); reads the input 42 followed by Enter, why does the next getchar() return 'n' instead of waiting for new input?
- 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)…