64,654
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <pthread.h>
#include <string.h>
#include <map>
using namespace std;
#define NUM_THREADS 5
void *countWordFrequency(void *str[100])
{
//将void类型转换成string类型
string s = (string)(char *)str;
int count = 0, c = 0, i, j = 0, k, space = 0;
char p[50][100], ptr1[50][100];
for (i = 0;i< s.length();i++)
{
if ((s[i] == ' ')||(s[i] == ',')||(s[i] == '.'))
{
space++;
}
}
for (i = 0, j = 0, k = 0;j < s.length();j++)
{
if ((s[j] == ' ')||(s[j] == 44)||(s[j] == 46))
{
p[i][k] = '\0';//把正在录入的设置成空格
i++;
k = 0;
}
else
p[i][k++] = s[j]; //str[j] probably is the array which store the words
//that are input into this vessel
//i probably the number of the paticular word
//j 是为了确认这个循环不超过单词的d总数量
}
k = 0; //
for (i = 0;i <= space;i++)
{
for (j = 0;j <= space;j++)
{
if (i == j)
{
strcpy(ptr1[k], p[i]);//ptr1[k] is the pointer to the destination
//array that the content is be copied.
//p[i] is the string to be copied.
//这个复制是复制一整个词而不是一个字母
k++;
count++;//i think the count is the number of the frequency words
break;
}
else
{
if (strcmp(ptr1[j], p[i]) != 0)//strcmp is the comparing function
//! = 0 means that they are paired
//successively
continue;//then continue means that if it satify the
//requirements then skip these sentence, restart the
//sentence from the beginning.
//so this continue means if ptr1 == p then step out
//this circle and restart
else
break;
}
}
}
for (i = 0;i < count;i++)
{
for (j = 0;j <= space;j++)
{
if (strcmp(ptr1[i], p[j]) == 0)
c++;
}
printf("%s -> %d times\n", ptr1[i], c);//ptr1[i] is the place to store the
//words of this code
c = 0;
}
pthread_exit(NULL);
return 0;
}
string readByLine()
{
char buffer[256];
fstream outFile;
outFile.open("book.txt",ios::in);
while(!outFile.eof())
{
outFile.getline(buffer,256,'\n');//getline(char *,int,char) 表示该行字符达到256个或遇到换行就结束
cout<<buffer<<endl;
}
outFile.close();
return 0;
}
int main ()
{
pthread_t threads[NUM_THREADS];
int indexes[NUM_THREADS];
int rc;
int i;
//read file
string r = readByLine();
for( i=0; i < NUM_THREADS; i++ ){
indexes[i] = i; //先保存i的值
// 传入的时候必须强制转换为void* 类型,即无类型指针
rc = pthread_create(&threads[i], NULL,
*countWordFrequency, (void *)&i);
if (rc){
cout << "Error: can create threads," << rc << endl;
exit(-1);
}
}
pthread_exit(NULL);
}