【问题标题】:sum of unlimited integers by taking Input from a file in C通过从 C 中的文件中获取输入来获得无限整数的总和
【发布时间】:2016-06-10 10:21:52
【问题描述】:

这里我的问题是计算从文​​件中获取输入的无限个整数的总和。文件在由空格分隔的行中包含无限个整数。如果这些,我还需要显示无效输入整数的输入包含任何其他字符或符号。我已经尝试过这段代码并且输出良好 这是我的代码....

void main()
{
  int i=1,j,a[100000],total=0,r=0;
  char discard,buffer[1024];
  FILE *fp;
  char filename[100];
  scanf("%s",filename);
  fp=fopen(filename,"r");
  do
  {
    fscanf(fp,"%1024s%c",buffer,&discard);
    r+=sscanf(buffer,"%d",&a[i]);
    total+=a[i++];
  } while(discard!='\n');
  if(r==i-1)
  {
    printf("\n%d",total);
  }
  else
    printf("\n Invalid Input");
}

代码执行良好。但这里的问题是代码超出了我的时间限制。请帮助我,以便我可以获得更好的代码

【问题讨论】:

  • 显示输入文件的前 3-4 行。
  • 对无限数量的整数求和总是需要无限的时间,因此违反了您的时间限制。
  • @ChristianJonassen OP 必须有一个惊人的硬盘驱动器,可以包含无限行数的文件... ;-)
  • 首先,c 中int 类型变量的范围是从-32768 到32767,因此您不能将大于32767 的值存储在int 类型的变量中。
  • 我的输入文件可以是1 2 3 4 5 6 7 8 9 0 1 23 3 5

标签: c


【解决方案1】:

您可以分块读取文件,从而加快读取整数的速度。有关提示,请查看此链接中的 fread() 示例(在链接页面中搜索例如“哨兵”):How do I process a text file in C by chunks of lines? 另外,请查看该答案的 cmets,例如做 malloc 而不是堆栈分配的好主意,也许使用二进制模式,注意关于 EOF 等的评论。

【讨论】:

    【解决方案2】:
    1. 获取文件大小
    2. 通过 malloc 分配动态内存缓冲区
    3. 将所有文件读入分配的内存缓冲区。
    4. 从内存缓冲区进行其他操作。

    【讨论】:

    • 但是内存没有问题。如果我的内存有问题,我可能会遇到一些其他错误,我在之前的状态中遇到过
    【解决方案3】:

    我不知道这是否会大大提高性能,但代码更具可读性并且我还删除了堆栈缓冲区的使用

    void main()
    {
      int value = 0, total = 0, r = 0;
      char discard;
      FILE *fp;
      char filename[100];
      scanf("%s",filename);
      fp = fopen(filename,"r");
      do
      {
        r = fscanf(fp, "%d%c", &value, &discard);
        if (r != 2 || (discard != ' ' && discard != '\n'))
        {
          printf("\n Invalid Input");
          return;
        }
        total += value;
      } while(discard != '\n');
      printf("\n%d", total);       
    }
    

    (请注意,它未经测试,但我有信心)

    【讨论】:

      猜你喜欢
      • 2021-12-04
      • 2016-06-30
      • 2023-03-21
      • 2012-06-11
      • 2017-02-02
      • 2017-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多