gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 09:03:02 25 4
gpt4 key购买 nike

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

我有这个:

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

最佳答案

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

关于c - 如何获取 C 中用户输入的历史记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11710256/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com