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 に答える