c - 我需要一种在 C 中两次读取 float 的方法。每次都以 <Ctrl>-d 结束

标签 c scanf stdin eof

我需要读入多项式的系数(作为 float )并用 ctrl-d 标记结尾。 然后我需要读入 x 值并显示 f(x)。也以 ctrl-d 结束。

到目前为止,我已经尝试使用 scanf 函数。读取系数效果很好,但在第一次键入 ctrl-d 后,scanf 将不会读取 x 值。

#include <stdio.h>


int main(){
    int count = 0;
    float poly[33];
    while(scanf("%f", &poly[count]) != EOF){   // reading the coeffs
        count++;
    }
    printf("Bitte Stellen zur Auswertung angeben\n");

    float x;
    float res;

    while(scanf("%f", &x) != EOF){   //Here it Fails. Since scanf still sees the EOF from before
        res = 0;
        for(int i = 1; i < count; i++){
            res += poly[i-1] * x + poly[i];
        }
        printf("Wert des Polynoms an der Stelle %f: %f\n", x, res);
    }
}

最佳答案

重新打开 stdin 可能会在第一次循环后起作用

freopen(NULL, "rb", stdin);

或者考虑 @Jonathan Leffler clearerr(stdin) 的想法。


如何不使用 Ctrld 结束输入(关闭 stdin),而是使用 Enter

创建一个函数来读取float

#include <ctype.h>
#include <stdbool.h>
#include <stdio.h>

int read_rest_of_line(FILE *stream) {
  int ch;
  do {
    ch = fgetc(stream);
  } while (ch != '\n' && ch != EOF);
  return ch;
}

// Read a line of input of float`s.  Return count
int read_line_of_floats(float *x, int n) {
  bool char_found = false;
  int count;
  for (count = 0; count < n; count++) {
    // Consume leading white-space looking for \n - do not let "%f" do it
    int ch;
    while (isspace((ch = getchar()))) {
      char_found = true;
      if (ch == '\n') {
        return count;
      }
    }
    if (ch == EOF) {
      return (count || char_found) ? count : EOF;
    }
    ungetc(ch, stdin);
    if (scanf("%f", &x[count]) != 1) {
      read_rest_of_line(stdin);
      return count;
    }
  }
  read_rest_of_line(stdin);
  return count;
}

上面仍然需要一些关于边缘情况的工作:n==0,当出现罕见的输入错误时,size_t,处理非数字输入等。< br/> 然后在需要 float 输入时使用它。

#define FN 33
int main(void) {
  float poly[FN];
  int count = read_line_of_floats(poly, FN);

  // Please specify positions for evaluation
  printf("Bitte Stellen zur Auswertung angeben\n");

  float x;
  float res;

  while (read_line_of_floats(&x, 1) == 1) {
    res = 0;
    for (int i = 1; i < count; i++) {
      res += poly[i - 1] * x + poly[i];
    }
    // Value of the polynomial at the location
    printf("Wert des Polynoms an der Stelle %f: %f\n", x, res);
  }
}

关于c - 我需要一种在 C 中两次读取 float 的方法。每次都以 <Ctrl>-d 结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56307136/

相关文章:

c - 使用 scanf 进行输入有困难

c - 这是 realloc() 的正确用法吗?

c - 如何将修改后的数组保存到文件中

c - Makefile目标文件生成、变量替换等问题

将字符串转换为十六进制

c - 简单的C scanf 不起作用?

c - 为什么调用函数会修改参数中未给出的指向函数的指针数组的值?

c - 在 C 语言的计算器程序中,输出以倒置的问号形式出现,并且提示出现两次

c - 标准输入中的文件结尾

docker - 在 Windows 上将标准输入通过管道传输到 docker exec