-4

我想编写一个程序来打印文件中找到的所有数字,然后将它们相加。我有两个问题:

  1. 如何将我打印的数字相加?
  2. 为什么在 output_file 中有这么多逗号: 多余的逗号

这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define CHUNK 12

char *getWord(FILE *infile);
void clean(char *dirty);

char *getWord(FILE *infile)
{
    char *word, *word2;
    int length, cursor, c;

    word = (char*)malloc(sizeof(char)*CHUNK);
    if(word == NULL) return NULL;

    length = CHUNK;
    cursor = 0;

    while(!isspace(c = getc(infile)) && !feof(infile))
    {
        word[cursor] = c;
        cursor++;

        if(cursor >= length)
        {
            length += CHUNK;

            word2 = (char*)realloc(word, cursor);
            if(word2 == NULL)
            {
                free(word2);
                return NULL;
            }
            else 
            {
                word = word2;
            }
        }
    }

    word[cursor] = '\0';
    return word;
}

void clean(char *dirty)
{
    int i = 0, j = 0; 
    char *temp;

    temp = strdup(dirty);
    while(i < strlen(temp))
    {
        if(isdigit(temp[i]))
        {
            dirty[j] = temp[i];
            j++;
        }

        i++;
    }

    dirty[j] = '\0';
    free(temp);
}

int main(int argc, char *argv[])
{

    char *word;
    FILE *infile, *outfile;

    if(argc != 3)
    {
        printf("Missing argument!\n");
        exit(1);
    }

    infile = fopen(argv[1], "r");
    if(infile != NULL)
    {

        outfile = fopen(argv[2], "w");
        if(outfile == NULL)
        {
            printf("Error, cannot open the outfile!\n");
            abort();
        }
        else 
        {
            while(!feof(infile))
            {
                word = getWord(infile);
                if(word == NULL)
                {
                    free(word);
                    abort();
                }

                clean(word);

                fputs(word, outfile);
                fputs(",", outfile);
                free(word);
            }
        }
    }
    else 
    {
        printf("Error, cannot open the outfile!\n");
        abort();
    }

    fclose(infile);
    fclose(outfile);
    return 0;
}

文件: 在此处输入图像描述

4

2 回答 2

1

,因为这个你得到-

fputs(",", outfile);
于 2013-09-01T02:02:29.670 回答
0

它在结构上与echounix 命令有关。该程序的核心可以简化为以下几行:

  int c, need_comma = 0;

  while ((c = fgetc(infile)) != EOF) {
    if (isdigit(c)) {
      fputc(c, outfile);
      need_comma = 1;
    }
    else {
      if (need_comma == 1) {
        fputc(',', outfile);
        need_comma = 0;
      }
    }
  }

这消除了对getWordclean功能的需求。

这只是印刷部分。中间文件为 CSV 格式,结构化且易于解析和添加数字(并将结果打印到另一个文件)。

于 2013-09-01T02:07:12.717 回答