The following code is taken from the English name of Linux Program Design: Beginning Linux Programming
# Include <stdio. h>
# Include <stdlib. h>
Char * menu [] = {
"A-add new record ",
"D-delete record ",
"Q-Quit ",
Null,
};
Int getchoice (char * greet, char * choices []);
Int main ()
{
Int choice = 0;
Do
{
Choice = getchoice ("Please select an action", menu );
Printf ("You have chosen: % C \ n", choice );
} While (choice! = 'Q ');
Exit (0 );
}
Int getchoice (char * greet, char * choices [])
{
Int chosen = 0;
{
Int chosen = 0;
Int selected;
Char ** option;
Do {
Printf ("Choice: % s \ n", greet );
Option = choices;
While (* option) // print menu
{
Printf ("% s \ n", * option );
Option ++;
}
Do {
Selected = getchar ();
} While (selected = '\ n ');
Option = choices;
While (* option)
{
If (selected = * option [0])
{
Chosen = 1;
Break;
}
Break;
}
Option ++;
}
If (! Chosen)
{
Printf ("Incorrect choice, select again \ n ");
}
} While (! Chosen );
Return selected;
}
Explanation: Linux is saving the input until the user presses enter, and then passing
The choice character and the subsequent enter to the program.
So, each time you enter a menu choice, the program CILS getchar, processes the character,
Then CILS getchar again, which immediately returns with the enter character.
Linux (like UNIX) uses a line feed to end lines of text. That is, uses a line feed alone to mean a newline, where
Other systems, such as MS-DOS, use a carriage return and a line feed together as a pair.
In Linux, user input is saved until the user presses the Enter key. Assume that you enter a and then press Enter.
The first getchar get a, 2nd getchar get '\ n', Linux uses' \ n' to replace a newline, And the MS-DOS uses "\ r \ n"
Note:
In the above Code
Do {
Selected = getchar ();
} While (selected = '\ n ');
Scenario: enter a and press Enter.
Explanation: When you press enter, because selected is '\ n', You can execute the DO statement again, that is, execute getchar for 2nd times, and the program will wait for user input.
Cleverly ignored '\ n '.