簡體   English   中英

在C中使用EOF的條件

[英]Condition using EOF in C

下面的代碼是我在K&R C編程語言中練習1-13的答案,它要求輸入中單詞長度的直方圖。 我的問題是關於EOF。 如何在不完全結束程序的情況下突破while循環? 我使用的是Ctrl-Z,我聽說它是​​Windows上的EOF,但這會結束程序,而不是僅僅打破while循環。 如何在while循環之后進入for循環而不結束文件? 這是一個普遍的問題,不僅僅是我的代碼,而是K&R中使用的所有代碼:while((c = getchar())!= EOF)。 提前致謝! `

#include <stdio.h>

#define MAXLENGTH 20 /* Max length of a word */
#define IN 1 /* In a word */
#define OUT 0 /* Out of a word */

int main() {
  int c, i, j, len = 0;
  int lenWords[MAXLENGTH];
  bool state = OUT;

  for (i = 0; i < MAXLENGTH; ++i) {
    lenWords[i] = 0;
  }

  c = getchar();
  while (c != EOF) {
    if (c != ' ' && c != '\n' && c != '\t') {
      if (state == IN) {
        lenWords[len - 1] += 1; /* a length 5 word is in subscript 4 */
        len = 0;
      }
      state = OUT;
    }
    else {
      state = IN;
    }
    if (state == IN) {
      len += 1;
    }
    c = getchar();
  }

  /* Generating a histogram using _ and | */
  for (i = 0; i < MAXLENGTH; ++i) { /* Underscores write over one another; not so efficient */
    for (j = 0; j < lenWords[i]; ++j) {
      putchar('_');
    }
    putchar('\n');
    for (j = 0; j < lenWords[i]; ++j) {
      putchar('_');
    }
    putchar('|');
    printf("Length: %d, Frequency: %d", i + 1, lenWords[i]);
  }

  return 0;
}

我認為你的問題屬於另一個網絡。

這里的答案: 相當於cmd.exe的^ D(在bash中)?

否。* nix上的Ctrl D會生成一個EOF,其中各種shell都會將其解釋為正在運行exit Windows上EOF的等效項是Ctrl Z ,但在提示符下鍵入時,cmd.exe不會特別解釋這一點。

按Ctrl + DEOF發送到標准輸入並停止* nix上的讀取。

看看這里

您必須檢查是否使用* nix或windows。

在Windows上,EOF由Ctrl+Z表示,而在* nix上EOF由Ctrl+D表示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM