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

时间:2012-07-29 15:02:39

标签: c user-input

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

我有这个:

#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;
}

2 个答案:

答案 0 :(得分:5)

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

答案 1 :(得分:2)

您必须使用readline之类的内容将本机功能本机添加到您的应用程序中。但是,大多数人只使用rlwrap

$ rlwrap your_prog