我用的语言是C语言,编程环境是VS STUDIO2017,首先我建立了一个功能菜单,可以通过switch选择功能,然后我用指针找到文件,然后打开文件,在对里面的字符一一进行判断,再输出对应功能的结果,代码如下:
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
int charcount = 0;
int wordcount = 0;
int linecount = 0;
void Charcount()
{
FILE *fp;
char a;
if ((fp = fopen("E:\\VS\\CODE\\WC\\wc.txt", "r")) == NULL)
{
printf("cannot open the file!\n");
exit(-1);
}
while (!feof(fp))
{
a = fgetc(fp);
if (a != ‘ ‘&&a != ‘\n‘&&a != ‘\t‘&&a != ‘,‘&&a != ‘.‘&&a != ‘!‘&&a != ‘;‘&&a != ‘=‘)
charcount++;
}
charcount--;
fclose(fp);
printf("Charcount:%d\n", charcount);
}
void Wordcount()
{
FILE *fp;
char a;
if ((fp = fopen("E:\\VS\\CODE\\WC\\wc.txt", "r")) == NULL)
{
printf("cannot open the file!\n");
exit(-1);
}
while (!feof(fp))
{
a = fgetc(fp);
if (a == ‘ ‘ || a == ‘\n‘ || a == ‘\t‘ || a == ‘,‘ || a == ‘.‘ || a == ‘!‘ || a == ‘=‘ || a == ‘;‘)
wordcount++;
}
fclose(fp);
printf("Wordcount:%d\n", wordcount);
}
void Linecount()
{
FILE *fp;
char a;
if ((fp = fopen("E:\\VS\\CODE\\WC\\wc.txt", "r")) == NULL)
{
printf("cannot open the file!\n");
exit(-1);
}
while (!feof(fp))
{
a = fgetc(fp);
if (a == ‘\n‘ || a == ‘\t‘)
linecount++;
}
linecount++;
fclose(fp);
printf("Linecount:%d\n", linecount);
}
void main()
{
int b = 0;
int c = 0;
printf("************WC************\n");
printf(" 1.字符计数 \n");
printf(" 2.单词计数 \n");
printf(" 3.行计数 \n");
printf(" 0.退出程序 \n");
printf("**************************\n");
printf("请输入对应功能的编号:\n");
scanf_s("%d", &b);
switch (b)
{
case 1:
Charcount();
break;
case 2:
Wordcount();
break;
case 3:
Linecount();
break;
case 0:
break;
default:
break;
}
printf(" 4.重新选择 \n");
printf(" 0.退出程序 \n");
printf("请输入对应功能的编号:\n");
scanf_s("%d", &c);
switch (c)
{
case 4:
main();
break;
case 0:
break;
default:
break;
}
}