// A program to demonstrate the use of the GNU readline package for
// improving the ease of interaction with a program.
// Michael Ashley / UNSW / 20 April 2004
#include <stdio.h>
#include <math.h>
// The following two lines are necessary for GNU readline:
#include <readline/readline.h>
#include <readline/history.h>
int main(void) {
char *cp;
float x;
int ret;
printf("This program calculates square roots\n");
// Loop forever (we will break out of the loop in certain conditions).
while (1) {
// Grab an input line from the user. readline automatically
// allocates space for the line, and returns a pointer to it. We
// store the pointer in our variable "cp".
cp = readline("please input a number (ENTER to exit) > ");
// If nothing was entered, readline gives us a NULL pointer. We
// test for this and exit the program.
if (cp == NULL) {
printf("\n");
break;
}
// Else we add the new line to the history buffer, so that the user
// can use the up/down arrow keys to navigate through previous
// responses.
add_history(cp);
// Now, try to read a floating point number from the input line.
// "ret" will be 1 if this worked; EOF at end-of-file; and something
// else if an error occurred.
ret = sscanf(cp, "%f", &x);
// We have now finished with the input line, so we free the space
// that readline() allocated for it ("man readline" explains why you
// should do this).
free(cp);
// Now check the results from sscanf.
if (ret == 1) {
printf ("The square root of %f is %f\n", x, sqrt(x));
} else if (ret == EOF) {
break;
} else {
printf ("that wasn't a valid number...\n");
}
}
return 0;
}
To compile the above program, do, e.g., "gcc example.c -lm -lreadline -lcurses".