如何在C中获取用户输入的历史记录



我有一个简单的计算器,可以不断输入新的数字并计算利润。但我希望能够使用箭头键(向上)来获取最后一个条目。

我有这个:

#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: %.3fn", 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[0mn");
        // Show [UP] if the estimate is positive
        else printf("33[32m [UP]33[0mn");
    }
    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: %.3fn", 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[0mn");
        // Show [UP] if the estimate is positive
        else printf("33[32m [UP]33[0mn");
        free(input);
    }
    return 0;
}

您可以使用GNU readline库,它提供行编辑和命令历史记录。这是该项目的主页。这似乎是你想要的。

您必须使用类似readline的东西来将该功能原生地添加到应用程序中。然而,大多数人只是使用rlwrap。

$ rlwrap your_prog

相关内容

  • 没有找到相关文章

最新更新