求文本文件单词计数程序 C语言

有没有人在啊,想请教一下,求文本文件单词计数程序 C语言
最新回答
暴力萌萌

2025-03-02 03:46:50

要求:

“Write a program that inputs the name of a file from user, creates a new file called “output.txt” to store the number of words and lines in the input file.”

代码如下:

#include <iostream.h>
#include <fstream.h>
#include "AfxWin.h"

Getlines(CString pathname)
{
CStdioFile file;
file.Open(pathname,CFile::modeRead);
int lines=0;
CString strLine;
while(file.ReadString(strLine))
{
strLine.TrimLeft();
strLine.TrimRight();
if(strLine != "") //这里去掉了空白行数,需要统计空白行数,则去掉.
{
lines ++;
}
}
file.Close();
return lines;
}

Getwords(CString pathName)
{
ifstream fout;
fout.open(pathName);
while(!fout)
{
cout<<"error to open file";
return 0;
}
char x;
BOOL flag=true;
int icount=0; // 做计数器
while(!fout.eof())
{
fout.read(&x,1); //一个字符一个字符的的读
if(((int)x>=65&&(int)x<=90)||((int)x>=97&&(int)x<=122)) //65~90为26个大写英文字母,97~122号为26个小写英文字母
{
if(flag)
icount++;
flag=false;
}
else
flag=true;
}
return icount;
}

int main()
{
char sfilename[100];
do{
cout<<"Input the file name:\n";
cin>>sfilename;
int words_num,lines_num;
words_num=Getwords(sfilename);
lines_num=Getlines(sfilename);
cout<<"The number of words is:"<<words_num<<"\n";
cout<<"The number of lines is:"<<lines_num<<"\n";
}
while(1);
return 0;
}

需要注意几点:

1:如果统计空白行,去掉if(strLine != "")
2:如果是一个字母算一个单词,在获得单词个数不需要那么麻烦
直接在if(字母)后面就加上icount++.目前这个是把空格区分开来的算一个单词
3:如果编译报错unresolved external symbol __endthreadex
请将VC6.0按照如下设置
“Project”->“settings”->“c/c++”
“Catagory” 选择“Code Generation”
“use run-time library”选择“debug multithreaded”
4:测试文件最好放在工程的目录,txt文档.比如1.txt。那么测试就输入1.txt
5:最最后我没有写output.txt,这个无所谓了把....
不玩心枉少年

2025-03-02 02:22:27

你的程序啥样子?
我想的是 把文本文件中每一个字符分别输出至一个字符变量,判断是不是字母,用计数器统计数目嘛。
#include<stdio.h>
int main()
{ FILE *fp;
char temp;
int box=0;
fp=fopen("temp.txt","w");
fprintf(fp,"%s","as72\n");/*这里是文本内容*/
fclose(fp);
fp=fopen("temp.txt","r");
while(1)
{ if(feof(fp)!=0) break;
fscanf(fp,"%c",&temp);
if((temp>='a'&&temp<='z')||(temp>='A'&&temp<='Z'))
box++;
}
fclose(fp);
printf("box=%d",box);
getch();
return 0;
}