c - 如何在 C 中读取多项式并将其存储在数组中并进行错误检查?

标签 c

该函数从标准输入读取多项式的系数并将其存储在给定的数组中。容量参数告诉函数 coeff[] 数组有多少系数空间。该函数尝试读取它可以读取的所有系数,直到到达文件末尾并返回它实际读取的系数数量。如果输入多项式不好(例如,系数太多或输入不能解析为 float ),此函数将打印“无效多项式”并以状态 101 退出程序。

输入文件是这样的:

0.0 6.0

25.00 -47.50 25.17 -5.00 0.33

前两个数字是绘图的范围,第二行表示多项式的系数。

这是我到目前为止的代码:

/**
 */

// Include our own header first
#include "poly.h"

// Then, anything else we need in the implementation file.
#include <stdlib.h>
#include <stdio.h>

/** Exit status if the input polynomail is bad. */
#define INVALID_POLYNOMAIL_STATUS 101

int readPoly( int capacity, double coeff[] )
{
   double variable = 0.0;

   int ch;

   int count = 0;
  while ( ( ch = getchar() ) != EOF ) {

    for(int i = 0; i < capacity; i++) {


         if(scanf("%lf", &variable) != 1) {

            fprintf(stderr, "Invalid input");
            exit(101);
         }

          else {

                  coeff[i] = variable;

                  count++;
               } 
    }
 }
 return count;
}

最佳答案

getchar 可能会读取一个值的开头,这是不正确的

一个简单的方法是停止任何错误(EOF 或错误值):

int readPoly( int capacity, double coeff[] )
{
   int i;

   for(i = 0; i < capacity; i++) {
      if (scanf("%lf", &coeff[i]) != 1)
        break;
   }

   return i;
}

另一种方法是手动绕过空格以指示错误:

int readPoly( int capacity, double coeff[] )
{
   int i;

   for (i = 0; i < capacity; i++) {
      for (;;) {
        int c;

        if ((c = getchar()) == EOF)
          return i;
        if (!isspace(c)) {
          ungetc(c, stdin);
          break;
      }
      if (scanf("%lf", &coeff[i]) != 1) {
        fprintf(stderr, "Invalid input");
        exit(101);
      }
   }

   return i;
}

注意counti是多余的,只需i就够了,也可以直接scanf进入数组

关于c - 如何在 C 中读取多项式并将其存储在数组中并进行错误检查?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54723854/

相关文章:

c - getaddrinfo() 中的段错误

c++ - Opencv C++到C接口(interface)函数转换

c - 如何按行和列对二维数组进行排序?

c - 查找具有不同实例的结构的地址

c - 有了操作系统安全性和执行禁用功能,用 C 语言编程是否变得更容易了?

c - 为什么我的 while() 语句陷入无限循环?

c - 高效的整数比较函数

c - 循环的执行速度随变量位置而变化

c - 在 'for' 循环初始值设定项中取消引用指针会产生段错误

c - 如何才能让 Actor 在困惑中脱颖而出