gpt4 book ai didi

C编程从文本中获取文本旁边的数字

转载 作者:行者123 更新时间:2023-11-30 19:09:27 24 4
gpt4 key购买 nike

我正在编写一个程序,需要从文本中获取金钱值,只要它旁边有“rsd”,例如:“20rsd,100rsd,500rsd..”

John has 20rsd, Danny has 30rsd. Bill gave 40rsd.

结果:90

我尝试了一些东西,但不知道该怎么做。顺便说一句,这是我的大学测试。

int main()
{
char c,d,f;
int price;
FILE *in;
char rsd[] = {'r','s','d'};

in = fopen("moneytext.txt","r");

while(!feof(in))
{
c = fgetc(in);
if(c=='r')
{
d = fgetc(in);
if(d == 's')
{
f = fgetc(in);
if(f == 'd')
printf("%c%c%c",c,d,f); //Prints rsd
}
}
}
//printf("%c",fgetc(in));
}

文本文件是这样的:

20.10.2017. John gave me 10rsd and Lisa gave me 30rsd, Danny gave me 50rsd, Nicholas donated 10rsd.

最佳答案

对于每个输入行,您可以递归地查找子字符串“rsd”,一旦找到一个:

  1. 反向查找数字即可得到价格
  2. 在当前“rsd”+3之后继续查找“rsd”

它可能看起来像:

while(fgets(buf, size, fd) != NULL)
{
char *start = buf;
/* search for rsd */
while(start = strstr(start, "rsd"))
{
p = start;

/* reverse find the start of price */
while(p > buf && IS_DIGIT(*(p-1)))
{
p--;
}
if(p < start)
{
while(p < start)
{
price = price * 10 + *p - '0';
}
/** do something about price here */
}
start += 3;
}
}

关于C编程从文本中获取文本旁边的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43251249/

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