2

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

我有这个:

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

2 回答 2

5

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

于 2012-07-29T15:04:49.840 回答
2

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

$ rlwrap your_prog
于 2012-07-29T15:05:00.460 回答