I need a way to read in floats twice in C. Each time ended by <Ctrl>-d

懵懂的女人 提交于 2019-12-24 18:32:20

问题


I need to read in the coefficients (as floats) of a polynomial and mark the end by ctrl-d. Then I need to read in x values and display f(x). Also ending that with ctrl-d.

So far I have tried it with the scanf function. Reading the coefficients work well but after typing ctrl-d the first time, scanf will not read in x values.

#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);
    }
}

回答1:


Re-opening stdin may work after the first loop

freopen(NULL, "rb", stdin);

Or consider @Jonathan Leffler idea of clearerr(stdin).


How about instead of using Ctrld to end input (which closes stdin), use Enter?

Create a function to read a line of 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;
}

Above still needs some work concerning edges cases: n==0, when a rare input error occurs, size_t, handling of non-numeric input, etc.
Then use it whenever float input is needed.

#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);
  }
}


来源:https://stackoverflow.com/questions/56307136/i-need-a-way-to-read-in-floats-twice-in-c-each-time-ended-by-ctrl-d

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!