Exiting a while loop at EOF using scanf in C

╄→гoц情女王★ 提交于 2019-11-28 02:26:26

The below code is a simplification of your I/O issues.

" %lf " supplies 3 scanf() format directives: 1) white-space 2) double specifier, 3) white-space.

The first white-space directive is not needed as the %lf allows for optional leading whitespace. The 2nd white-space directive causes problems as it consumes the Enter key, waiting for additional input.

"%lf" supplies 1 scanf() format directives: double specifier

This consumes optional leading white-space, including any previous \n, then scans for and hopefully decodes a double. A \n (Enter key) following the number is left in the input buffer for the next input (the next scanf()).


Now as to why your control Z is failing. It appears your console is consuming the ^Z and performing a "suspend job". My console, instead of giving the ^Z to the program, closes the stdin input. In essence putting an EOF in stdin.

So you need to either:
1) Find your console's mechanism for closing the stdin - others have suggested ^D.
2) Use an alternative to exit your loop. I suggest result != 1 which readily occurs when non-numeric input is entered.

#include <stdio.h>
int main(int argc, char *argv[]) {
  int result;
  double x = 0.0;
  do {
    // result = scanf(" %lf ", &x);  /* Your original format */
    result = scanf("%lf", &x);
    printf("%d %lf\n", result, x);
    fflush(stdout);  // Your system may not need this flush
  } while (result != EOF);
}

Okay guys, after giving up on this first part of the project and debugging the other parts, I have determined that my only issue with the code above is I am trying to reference an index of an array that is out of bounds. I have also determined that the EOF key is ctrl-d, even though I have read and been told by my professor that it is ctrl-z for windows. Regardless, this should be an easy fix. Thanks so much to everyone who provided input!

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