本程序改變自:http://blog.csdn.net/zhixi1050/article/details/72718638
語言:C++
編譯環境:visual studio 2015
運行環境:Win10
做出修改的地方:在原碼基礎上修改了記錄行數的功能,刪去了不完整行數的記錄,直接顯示行數。
修改后的代碼如下:
#include <stdio.h>
//#include <stdlib.h>
#include <ctype.h>//為isspace()提供原型
#include <stdbool.h>
#define STOP '|' //定義結束標志
int main(void)
{
?? ?char c;
?? ?char prev;//讀取的前一個字符
?? ?long n_chars = 0L;??????//字符數
?? ?int n_lines = 0;????? ? ? ? //行數
?? ?int n_words = 0;???? ? ?? //單詞數
?? ?bool inword = false;??????//字符在單詞中,inward等于ture
?? ?printf("請輸入字符( | 用于結束輸入):\n");
?? ?prev = '\n';//識別完整的行
?? ?while ((c = getchar()) != STOP)??????//當讀取的字符不為結束字符時
?? ?{
?? ??? ?n_chars++??????;//統計字符數
?? ??? ?if (c == '\n')
?? ??? ??? ?n_lines++;??????//統計行
?? ??? ?if (!isspace(c) && !inword)
?? ??? ?{
?? ??? ??? ?inword = true;??????//開始一個新單詞;
?? ??? ??? ?n_words++;??????//統計單詞
?? ??? ?}
?? ??? ?if (isspace(c) && inword)
?? ??? ??? ?inword = false;??????//打到單詞的結尾
?? ??? ?prev = c;
?? ?}
?? ?if (prev != '\n')
?? ??? ?n_lines ++;
?? ?printf("字母數目=%ld,單詞數=%d,行數=%d,", n_chars, n_words, n_lines);
?? ?return 0;
}