行数を数える #1
行数とは一連の文字列データに含まれる改行の数とする。
ただし文字列の最後が改行でない場合は改行の数に1を加えたものを行数とする。
また一文字もない場合は行数は0であるとする。
標準入力からデータを読み込み行数を数え表示するプログラム。
#include <stdio.h> int main(void) { unsigned int nlines = 0, is_prev_eol = 0, is_zero_file = 1; for (;;) { int c = getchar(); if (c == EOF) break; is_zero_file = 0; if (c == '\n') { is_prev_eol = 1; ++nlines; } else { is_prev_eol = 0; } } if (! is_zero_file && ! is_prev_eol) ++nlines; printf("%u\n", nlines); return 0; }