As a preface, I have done my best to read through the FAQs on this forum so if I am violating the forum rules it's not out of negligence.
That said, I have a question regarding how the getchar() function in the stdio library works. For contextual purposes, I am writing a simple program that takes input from the terminal (stdin) and stores the inputted characters into a consolidated C string.
Code:
1 #include <stdio.h>
2
3 #define MAX_LENGTH 10
4
5 int readbuff(char[]);
6
7 main()
8 {
9 char buff[MAX_LENGTH];
10
11 readbuff(buff);
12 printf("%s", buff);
13
14 return 0;
15 }
16
17 /* read buffer and return the number of characters input */
18 int readbuff(char buff[])
19 {
20 int c, i;
21
22 for(i = 0; i < MAX_LENGTH - 1 && (c = getchar()) != EOF && c != '\n'; ++i)
23 buff[i] = c;
24 if(c == '\n')
25 buff[i++] = c;
26 buff[i++] = '\0';
27
28 return i;
29 }
In short, my question is what exactly happens when the user presses the Enter key? I am wondering if the reaction is relative to the OS, or if there is some standard signal that is sent when this key is pressed. I am aware that the newline character, '\n', is appended to the end of the current string of characters, but why does it also cause the program to start executing the getchar() function inside of the for loop?
I am running Ubuntu 11.04 with the BASH if that makes a difference.