我有一个简单的计算器,可以让我不断输入新数字并计算出利润金额。但我希望能够使用箭头键(向上)来获取最后一个条目。
我有这个:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
// ------------------------------------------------
int main (int argCount, char *argv[]) {
float
shares = atof(argv[1]),
price = atof(argv[2]),
// Commission fees
fee = 4.95,
// Total price paid (counts buy + sell commission)
base = (price * shares) + (fee * 2),
profit;
printf("TOTAL BUY: %.3f\n", base);
/**
* Catch the input and calculate the
* gain based on the new input.
*/
char sell[32];
while (1) {
printf(": ");
fflush(stdout);
fgets(sell, sizeof(sell), stdin);
profit = (atof(sell) * shares) - base;
printf(": %.3f", profit);
// Show [DOWN] if the estimate is negative
if (profit < 0)
printf("\33[31m [DOWN]\33[0m\n");
// Show [UP] if the estimate is positive
else printf("\33[32m [UP]\33[0m\n");
}
return 0;
}
更新:答案如下。
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <readline/readline.h>
#include <readline/history.h>
// ------------------------------------------------
int main (int argCount, char *argv[]) {
float
shares = atof(argv[1]),
price = atof(argv[2]),
// Commission fees
fee = 4.95,
// Total price paid
base = (price * shares) + (fee * 2),
profit;
printf("TOTAL BUY: %.3f\n", base);
/**
* Catch the users input and calculate the
* gain based on the new input.
*
* This makes it easy for active traders or
* investors to calculate a proposed gain.
*/
char* input, prompt[100];
for(;;) {
rl_bind_key('\t', rl_complete);
snprintf(prompt, sizeof(prompt), ": ");
if (!(input = readline(prompt)))
break;
add_history(input);
profit = (atof(input) * shares) - base;
printf(": %.3f", profit);
// Show [DOWN] if the estimate is negative
if (profit < 0)
printf("\33[31m [DOWN]\33[0m\n");
// Show [UP] if the estimate is positive
else printf("\33[32m [UP]\33[0m\n");
free(input);
}
return 0;
}