Question
Answer and Explanation
In the context of terminal input in C, a "scanline" typically refers to a line of text entered by the user before they press the Enter key. The input that signals the end of this scanline is the newline character, represented as \n
.
When you use functions like scanf
, fgets
, or getchar
to read input from the standard input stream (usually the keyboard), the newline character acts as a delimiter.
Here’s how different functions handle it:
1. scanf
:
- With format specifiers like %s
, scanf
reads characters until it encounters whitespace (including newline). The newline character is left in the input buffer.
- Example:
#include <stdio.h>
int main() {
char str[100];
printf("Enter a string: ");
scanf("%s", str);
printf("You entered: %s\n", str);
return 0;
}
- If you type "Hello World" and press Enter, scanf
with %s
will only read "Hello", leaving " World\n" in the buffer.
2. fgets
:
- fgets
reads characters until it encounters a newline character or reaches the specified maximum number of characters. It includes the newline character in the string, if it was encountered before reaching the maximum length.
- Example:
#include <stdio.h>
int main() {
char str[100];
printf("Enter a line: ");
fgets(str, sizeof(str), stdin);
printf("You entered: %s", str);
return 0;
}
- If you type "Hello World" and press Enter, fgets
will read "Hello World\n".
3. getchar
:
- getchar
reads a single character from the input stream, including the newline character.
- Example:
#include <stdio.h>
int main() {
int ch;
printf("Enter a character: ");
ch = getchar();
printf("You entered: %c\n", ch);
return 0;
}
- If you press 'A' and then Enter, getchar
will first read 'A', and the next call to getchar
will read '\n'.
In summary, the newline character (\n
), generated by pressing the Enter key, is the typical input used to signal the end of a scanline in C. The way it's handled depends on the specific input function used.