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

时间:2017-04-06 09:34:57

标签: c text char getchar

我正在编写一个程序,需要从文本中获取金钱价值,当有#34; 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));
}

Textfile是这样的:

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

2 个答案:

答案 0 :(得分:1)

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

  1. 反向查找数字以获得价格
  2. 在当前“rsd”+3
  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;
        }
    }
    

答案 1 :(得分:0)

代码可以循环查找N个条件中的1个

  1. 找到一个数字:累加整数值price

  2. 找到后缀模式中的单个字符匹配:前进到下一个字符。如果找到整个模式,请添加price

  3. 都不是。重置模式和价格。

  4. 继续,直到EOF找到。

  5. int main() {
      // Use a string to include \0 to denote when to stop match
      const char *rsd = "rsd";
    
      FILE *out = fopen("moneytext.txt", "w");
      fputs("123 John has 20rsd, Danny456 has 30rsd. Bill789 gave 40rsd", out);
      fclose(out);
    
      FILE *in = fopen("moneytext.txt", "r");
      if (in) {
        // fgetc() return an int, typically 1 of 257 different values, char is insufficient.
        int c;
        int sum = 0;
        int price = 0;
        const char *pattern = rsd;
        while ((c = fgetc(in)) != EOF) {
          if (isdigit(c)) {
            price = price * 10 + c - '0';
            pattern = rsd;
          } else if (c == (unsigned char) *pattern) {
            pattern++;
            if (*pattern == '\0') {
              pattern = rsd;
              sum += price;
              price = 0;
            }
          } else {
            pattern = rsd;
            price = 0;
          }
        }
        fclose(in);
        printf("Sum:%d\n", sum);
      }
    }
    

    输出

    Sum:90
    

    需要额外的代码来处理负数,检测int溢出,FILE错误等。