读书人

求一段c++的源代码: 分析一个文件中的

发布时间: 2012-02-15 12:09:44 作者: rapoo

求一段c++的源代码: 分析一个文件中的总单词数等,高分相送!!!在线等待

分析源程序中文件,统计:
1 文件中的总单词数
2 文件中的关键字“if”“while”“case”出现的次数
3 源程序文件行数

文件访问库函数:frendc( ) fscanf( ) fget( )

过去学c++的时候,做过类似的,现在没时间做,谁有现成的代码,发下啊,
谢谢,分不够可以再开贴^_^

[解决办法]
读文件的行统计单词数

int main()
{
ifstream infile;
string filename;
cout < < "Please enter the file name: ";
cin > > filename;

infile.open(filename.c_str());
string line;
getline(infile, line, '\n ');
infile.close();

vector <string> wordsOfLine;
string::size_type pos = 0, prev_pos =0;
string word;
while ((pos = line.find_first_of( ' ', pos)) != string::npos)
{
word = line.substr(prev_pos, pos - prev_pos);
prev_pos = ++pos;
wordsOfLine.push_back(word);
}
wordsOfLine.push_back(line.substr(prev_pos, pos - prev_pos));

size_t numOfLine = wordsOfLine.size();
cout < < numOfLine < < "words " < < endl;
}
[解决办法]
http://topic.csdn.net/t/20020602/04/772103.html
[解决办法]
sorry 看岔了,以为是普通的E文文件统计 ...

如果只是统计源程序文件:
1 文件中的总单词数
2 文件中的关键字“if”“while”“case”出现的次数
3 源程序文件行数

不做其他工作, 那么这样吧:【做了少量修改】
#include <fstream>
#include <string>
#include <iostream>
#include <cstdlib>
#include <map>

using namespace std;

//#include <string.h>
//#include <stdio.h> #include <stdlib.h>

int main()
{
ifstream ifile( "test.txt ");
map <string, int> strmap; // 定义map
map <string, int> ::iterator it;// 定义map迭代器
string str, w;
int line=0, words=0, i;

/* 构造单词字符集*/
string pum( "_ ");
for(i= 'A '; i < 'Z '+1; i++) pum+=i;
for(i= 'a '; i < 'z '+1; i++) pum+=i;
for(i= '0 '; i < '9 '+1; i++) pum+=i;

string::size_type index, end;
while(!ifile.eof())
{
getline(ifile, str);
line++;
index=str.find_first_of(pum); //寻找单词起点
while(index != string::npos)
{
end = str.find_first_not_of(pum, index); //寻找单词终点
words++; //++
w = str.substr(index, end-index); //截取单词
it = strmap.find(w);
if(it == strmap.end())
strmap.insert(make_pair(w, 1));
else it-> second++;

if(end == string::npos)break; //如果行结束, 则break跳出
else
index=str.find_first_of(pum, end); //否则寻找下一个起点
}
}

cout < < "Result: " < <endl
< < "Total line(s) is: " < <line < <endl
< < "Total word(s) is: " < <words < <endl
< < "Count word \ "if\ ": " < <strmap[ "if "] < <endl
< < "Count word \ "while\ ": " < <strmap[ "while "] < <endl
< < "Count word \ "case\ ": " < <strmap[ "case "] < <endl;



cout < <endl < < "There are such word(s) in this file: " < <endl;
for(it = strmap.begin(); it!=strmap.end(); it++)
cout < < "Word:\ " " < <it-> first < < "\ ", Count: " < <it-> second < <endl;
system( "pause ");
return 0;
}

test.txt内容:
int main()
{
int i;
printf( "if case while\n ");

return 0;
}

注: 程序没有处理 注释, 如果需要处理注释,自己再增加这个功能吧
[解决办法]
这种处理方法怎么样?
读出文件中的每一行,在行首和行尾加上Space,拼成一个String。
然后将String中的每2个Space都替换成1个Space,直到没有得替换为止。
对这个缩减后的String,数一下其中的Space的个数,再-1就是单词数了。
当然没有考虑其中有符号的情况,权做是参考。
[解决办法]
up了
[解决办法]
up!
[解决办法]
mark

读书人网 >C++

热点推荐